Initial commit: ROW Client source code

Game client codebase including:
- CharacterActionControl: Character and creature management
- GlobalScript: Network, items, skills, quests, utilities
- RYLClient: Main client application with GUI and event handlers
- Engine: 3D rendering engine (RYLGL)
- MemoryManager: Custom memory allocation
- Library: Third-party dependencies (DirectX, boost, etc.)
- Tools: Development utilities

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2025-11-29 16:24:34 +09:00
commit e067522598
5135 changed files with 1745744 additions and 0 deletions

View File

@@ -0,0 +1,271 @@
//------------------------------------------------------------------------------
// File: AsyncIo.h
//
// Desc: DirectShow sample code - base library for I/O functionality.
//
// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved.
//------------------------------------------------------------------------------
#ifndef __ASYNCIO_H__
#define __ASYNCIO_H__
//
// definition of CAsyncFile object that performs file access. It provides
// asynchronous, unbuffered, aligned reads from a file, using a worker thread
// on win95 and potentially overlapped i/o if available.
// !!! Need to use real overlapped i/o if available
// currently only uses worker thread, not overlapped i/o
class CAsyncIo;
class CAsyncStream;
//
// Model the stream we read from based on a file-like interface
//
class CAsyncStream
{
public:
virtual ~CAsyncStream() {};
virtual HRESULT SetPointer(LONGLONG llPos) = 0;
virtual HRESULT Read(PBYTE pbBuffer,
DWORD dwBytesToRead,
BOOL bAlign,
LPDWORD pdwBytesRead) = 0;
virtual LONGLONG Size(LONGLONG *pSizeAvailable = NULL) = 0;
virtual DWORD Alignment() = 0;
virtual void Lock() = 0;
virtual void Unlock() = 0;
//virtual void SetStopHandle(HANDLE hevStop) {}
};
// represents a single request and performs the i/o. Can be called on either
// worker thread or app thread, but must hold pcsFile across file accesses.
// (ie across SetFilePointer/ReadFile pairs)
class CAsyncRequest
{
CAsyncIo *m_pIo;
CAsyncStream *m_pStream;
LONGLONG m_llPos;
BOOL m_bAligned;
LONG m_lLength;
BYTE* m_pBuffer;
LPVOID m_pContext;
DWORD m_dwUser;
HRESULT m_hr;
public:
// init the params for this request. Issue the i/o
// if overlapped i/o is possible.
HRESULT Request(
CAsyncIo *pIo,
CAsyncStream *pStream,
LONGLONG llPos,
LONG lLength,
BOOL bAligned,
BYTE* pBuffer,
LPVOID pContext, // filter's context
DWORD dwUser); // downstream filter's context
// issue the i/o if not overlapped, and block until i/o complete.
// returns error code of file i/o
HRESULT Complete();
// cancels the i/o. blocks until i/o is no longer pending
HRESULT Cancel()
{
return S_OK;
};
// accessor functions
LPVOID GetContext()
{
return m_pContext;
};
DWORD GetUser()
{
return m_dwUser;
};
HRESULT GetHResult() {
return m_hr;
};
// we set m_lLength to the actual length
LONG GetActualLength() {
return m_lLength;
};
LONGLONG GetStart() {
return m_llPos;
};
};
typedef CGenericList<CAsyncRequest> CRequestList;
// this class needs a worker thread, but the ones defined in classes\base
// are not suitable (they assume you have one message sent or posted per
// request, whereas here for efficiency we want just to set an event when
// there is work on the queue).
//
// we create CAsyncRequest objects and queue them on m_listWork. The worker
// thread pulls them off, completes them and puts them on m_listDone.
// The events m_evWork and m_evDone are set when the corresponding lists are
// not empty.
//
// Synchronous requests are done on the caller thread. These should be
// synchronised by the caller, but to make sure we hold m_csFile across
// the SetFilePointer/ReadFile code.
//
// Flush by calling BeginFlush. This rejects all further requests (by
// setting m_bFlushing within m_csLists), cancels all requests and moves them
// to the done list, and sets m_evDone to ensure that no WaitForNext operations
// will block. Call EndFlush to cancel this state.
//
// we support unaligned calls to SyncRead. This is done by opening the file
// twice if we are using unbuffered i/o (m_dwAlign > 1).
// !!!fix this to buffer on top of existing file handle?
class CAsyncIo
{
CCritSec m_csReader;
CAsyncStream *m_pStream;
CCritSec m_csLists; // locks access to the list and events
BOOL m_bFlushing; // true if between BeginFlush/EndFlush
CRequestList m_listWork;
CRequestList m_listDone;
CAMEvent m_evWork; // set when list is not empty
CAMEvent m_evDone;
// for correct flush behaviour: all protected by m_csLists
LONG m_cItemsOut; // nr of items not on listDone or listWork
BOOL m_bWaiting; // TRUE if someone waiting for m_evAllDone
CAMEvent m_evAllDone; // signal when m_cItemsOut goes to 0 if m_cWaiting
CAMEvent m_evStop; // set when thread should exit
HANDLE m_hThread;
LONGLONG Size() {
ASSERT(m_pStream != NULL);
return m_pStream->Size();
};
// start the thread
HRESULT StartThread(void);
// stop the thread and close the handle
HRESULT CloseThread(void);
// manage the list of requests. hold m_csLists and ensure
// that the (manual reset) event hevList is set when things on
// the list but reset when the list is empty.
// returns null if list empty
CAsyncRequest* GetWorkItem();
// get an item from the done list
CAsyncRequest* GetDoneItem();
// put an item on the work list
HRESULT PutWorkItem(CAsyncRequest* pRequest);
// put an item on the done list
HRESULT PutDoneItem(CAsyncRequest* pRequest);
// called on thread to process any active requests
void ProcessRequests(void);
// initial static thread proc calls ThreadProc with DWORD
// param as this
static DWORD WINAPI InitialThreadProc(LPVOID pv) {
CAsyncIo * pThis = (CAsyncIo*) pv;
return pThis->ThreadProc();
};
DWORD ThreadProc(void);
public:
CAsyncIo(CAsyncStream *pStream);
~CAsyncIo();
// open the file
HRESULT Open(LPCTSTR pName);
// ready for async activity - call this before
// calling Request
HRESULT AsyncActive(void);
// call this when no more async activity will happen before
// the next AsyncActive call
HRESULT AsyncInactive(void);
// queue a requested read. must be aligned.
HRESULT Request(
LONGLONG llPos,
LONG lLength,
BOOL bAligned,
BYTE* pBuffer,
LPVOID pContext,
DWORD dwUser);
// wait for the next read to complete
HRESULT WaitForNext(
DWORD dwTimeout,
LPVOID *ppContext,
DWORD * pdwUser,
LONG * pcbActual
);
// perform a read of an already aligned buffer
HRESULT SyncReadAligned(
LONGLONG llPos,
LONG lLength,
BYTE* pBuffer,
LONG* pcbActual,
PVOID pvContext
);
// perform a synchronous read. will be buffered
// if not aligned.
HRESULT SyncRead(
LONGLONG llPos,
LONG lLength,
BYTE* pBuffer);
// return length
HRESULT Length(LONGLONG *pllTotal, LONGLONG* pllAvailable);
// all Reader positions, read lengths and memory locations must
// be aligned to this.
HRESULT Alignment(LONG* pl);
HRESULT BeginFlush();
HRESULT EndFlush();
LONG Alignment()
{
return m_pStream->Alignment();
};
BOOL IsAligned(LONG l) {
if ((l & (Alignment() -1)) == 0) {
return TRUE;
} else {
return FALSE;
}
};
BOOL IsAligned(LONGLONG ll) {
return IsAligned( (LONG) (ll & 0xffffffff));
};
// Accessor
HANDLE StopEvent() const { return m_evDone; }
};
#endif // __ASYNCIO_H__

View File

@@ -0,0 +1,226 @@
//------------------------------------------------------------------------------
// File: AsyncRdr.h
//
// Desc: DirectShow sample code - base library for I/O functionality.
//
// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved.
//------------------------------------------------------------------------------
#ifndef __ASYNCRDR_H__
#define __ASYNCRDR_H__
//
// AsyncRdr
//
// Defines an IO source filter.
//
// This filter (CAsyncReader) supports IBaseFilter and IFileSourceFilter interfaces from the
// filter object itself. It has a single output pin (CAsyncOutputPin)
// which supports IPin and IAsyncReader.
//
// This filter is essentially a wrapper for the CAsyncFile class that does
// all the work.
//
// the filter class (defined below)
class CAsyncReader;
// the output pin class
class CAsyncOutputPin
: public IAsyncReader,
public CBasePin
{
protected:
CAsyncReader* m_pReader;
CAsyncIo * m_pIo;
// This is set every time we're asked to return an IAsyncReader
// interface
// This allows us to know if the downstream pin can use
// this transport, otherwise we can hook up to thinks like the
// dump filter and nothing happens
BOOL m_bQueriedForAsyncReader;
HRESULT InitAllocator(IMemAllocator **ppAlloc);
public:
// constructor and destructor
CAsyncOutputPin(
HRESULT * phr,
CAsyncReader *pReader,
CAsyncIo *pIo,
CCritSec * pLock);
~CAsyncOutputPin();
// --- CUnknown ---
// need to expose IAsyncReader
DECLARE_IUNKNOWN
STDMETHODIMP NonDelegatingQueryInterface(REFIID, void**);
// --- IPin methods ---
STDMETHODIMP Connect(
IPin * pReceivePin,
const AM_MEDIA_TYPE *pmt // optional media type
);
// --- CBasePin methods ---
// return the types we prefer - this will return the known
// file type
HRESULT GetMediaType(int iPosition, CMediaType *pMediaType);
// can we support this type?
HRESULT CheckMediaType(const CMediaType* pType);
// Clear the flag so we see if IAsyncReader is queried for
HRESULT CheckConnect(IPin *pPin)
{
m_bQueriedForAsyncReader = FALSE;
return CBasePin::CheckConnect(pPin);
}
// See if it was asked for
HRESULT CompleteConnect(IPin *pReceivePin)
{
if (m_bQueriedForAsyncReader) {
return CBasePin::CompleteConnect(pReceivePin);
} else {
#ifdef VFW_E_NO_TRANSPORT
return VFW_E_NO_TRANSPORT;
#else
return E_FAIL;
#endif
}
}
// Remove our connection status
HRESULT BreakConnect()
{
m_bQueriedForAsyncReader = FALSE;
return CBasePin::BreakConnect();
}
// --- IAsyncReader methods ---
// pass in your preferred allocator and your preferred properties.
// method returns the actual allocator to be used. Call GetProperties
// on returned allocator to learn alignment and prefix etc chosen.
// this allocator will be not be committed and decommitted by
// the async reader, only by the consumer.
STDMETHODIMP RequestAllocator(
IMemAllocator* pPreferred,
ALLOCATOR_PROPERTIES* pProps,
IMemAllocator ** ppActual);
// queue a request for data.
// media sample start and stop times contain the requested absolute
// byte position (start inclusive, stop exclusive).
// may fail if sample not obtained from agreed allocator.
// may fail if start/stop position does not match agreed alignment.
// samples allocated from source pin's allocator may fail
// GetPointer until after returning from WaitForNext.
STDMETHODIMP Request(
IMediaSample* pSample,
DWORD dwUser); // user context
// block until the next sample is completed or the timeout occurs.
// timeout (millisecs) may be 0 or INFINITE. Samples may not
// be delivered in order. If there is a read error of any sort, a
// notification will already have been sent by the source filter,
// and STDMETHODIMP will be an error.
STDMETHODIMP WaitForNext(
DWORD dwTimeout,
IMediaSample** ppSample, // completed sample
DWORD * pdwUser); // user context
// sync read of data. Sample passed in must have been acquired from
// the agreed allocator. Start and stop position must be aligned.
// equivalent to a Request/WaitForNext pair, but may avoid the
// need for a thread on the source filter.
STDMETHODIMP SyncReadAligned(
IMediaSample* pSample);
// sync read. works in stopped state as well as run state.
// need not be aligned. Will fail if read is beyond actual total
// length.
STDMETHODIMP SyncRead(
LONGLONG llPosition, // absolute file position
LONG lLength, // nr bytes required
BYTE* pBuffer); // write data here
// return total length of stream, and currently available length.
// reads for beyond the available length but within the total length will
// normally succeed but may block for a long period.
STDMETHODIMP Length(
LONGLONG* pTotal,
LONGLONG* pAvailable);
// cause all outstanding reads to return, possibly with a failure code
// (VFW_E_TIMEOUT) indicating they were cancelled.
// these are defined on IAsyncReader and IPin
STDMETHODIMP BeginFlush(void);
STDMETHODIMP EndFlush(void);
};
//
// The filter object itself. Supports IBaseFilter through
// CBaseFilter and also IFileSourceFilter directly in this object
class CAsyncReader : public CBaseFilter
{
protected:
// filter-wide lock
CCritSec m_csFilter;
// all i/o done here
CAsyncIo m_Io;
// our output pin
CAsyncOutputPin m_OutputPin;
// Type we think our data is
CMediaType m_mt;
public:
// construction / destruction
CAsyncReader(
TCHAR *pName,
LPUNKNOWN pUnk,
CAsyncStream *pStream,
HRESULT *phr);
~CAsyncReader();
// --- CBaseFilter methods ---
int GetPinCount();
CBasePin *GetPin(int n);
// --- Access our media type
const CMediaType *LoadType() const
{
return &m_mt;
}
virtual HRESULT Connect(
IPin * pReceivePin,
const AM_MEDIA_TYPE *pmt // optional media type
)
{
return m_OutputPin.CBasePin::Connect(pReceivePin, pmt);
}
};
#endif //__ASYNCRDR_H__

View File

@@ -0,0 +1,211 @@
//-----------------------------------------------------------------------------
// File: D3DApp.h
//
// Desc: Application class for the Direct3D samples framework library.
//
// Copyright (c) 1998-2001 Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#ifndef D3DAPP_H
#define D3DAPP_H
// basetsd.h defines INT_PTR (used below). It is not included by default
// under VC 5.0. If you are using VC6 or later, it is included via Windows.h.
#include <basetsd.h>
//-----------------------------------------------------------------------------
// Error codes
//-----------------------------------------------------------------------------
enum APPMSGTYPE { MSG_NONE, MSGERR_APPMUSTEXIT, MSGWARN_SWITCHEDTOREF };
#define D3DAPPERR_NODIRECT3D 0x82000001
#define D3DAPPERR_NOWINDOW 0x82000002
#define D3DAPPERR_NOCOMPATIBLEDEVICES 0x82000003
#define D3DAPPERR_NOWINDOWABLEDEVICES 0x82000004
#define D3DAPPERR_NOHARDWAREDEVICE 0x82000005
#define D3DAPPERR_HALNOTCOMPATIBLE 0x82000006
#define D3DAPPERR_NOWINDOWEDHAL 0x82000007
#define D3DAPPERR_NODESKTOPHAL 0x82000008
#define D3DAPPERR_NOHALTHISMODE 0x82000009
#define D3DAPPERR_NONZEROREFCOUNT 0x8200000a
#define D3DAPPERR_MEDIANOTFOUND 0x8200000b
#define D3DAPPERR_RESIZEFAILED 0x8200000c
#define D3DAPPERR_NULLREFDEVICE 0x8200000d
//-----------------------------------------------------------------------------
// Name: struct D3DModeInfo
// Desc: Structure for holding information about a display mode
//-----------------------------------------------------------------------------
struct D3DModeInfo
{
DWORD Width; // Screen width in this mode
DWORD Height; // Screen height in this mode
D3DFORMAT Format; // Pixel format in this mode
DWORD dwBehavior; // Hardware / Software / Mixed vertex processing
D3DFORMAT DepthStencilFormat; // Which depth/stencil format to use with this mode
};
//-----------------------------------------------------------------------------
// Name: struct D3DDeviceInfo
// Desc: Structure for holding information about a Direct3D device, including
// a list of modes compatible with this device
//-----------------------------------------------------------------------------
struct D3DDeviceInfo
{
// Device data
D3DDEVTYPE DeviceType; // Reference, HAL, etc.
D3DCAPS8 d3dCaps; // Capabilities of this device
const TCHAR* strDesc; // Name of this device
BOOL bCanDoWindowed; // Whether this device can work in windowed mode
// Modes for this device
DWORD dwNumModes;
D3DModeInfo modes[150];
// Current state
DWORD dwCurrentMode;
BOOL bWindowed;
D3DMULTISAMPLE_TYPE MultiSampleTypeWindowed;
D3DMULTISAMPLE_TYPE MultiSampleTypeFullscreen;
};
//-----------------------------------------------------------------------------
// Name: struct D3DAdapterInfo
// Desc: Structure for holding information about an adapter, including a list
// of devices available on this adapter
//-----------------------------------------------------------------------------
struct D3DAdapterInfo
{
// Adapter data
D3DADAPTER_IDENTIFIER8 d3dAdapterIdentifier;
D3DDISPLAYMODE d3ddmDesktop; // Desktop display mode for this adapter
// Devices for this adapter
DWORD dwNumDevices;
D3DDeviceInfo devices[5];
// Current state
DWORD dwCurrentDevice;
};
//-----------------------------------------------------------------------------
// Name: class CD3DApplication
// Desc: A base class for creating sample D3D8 applications. To create a simple
// Direct3D application, simply derive this class into a class (such as
// class CMyD3DApplication) and override the following functions, as
// needed:
// OneTimeSceneInit() - To initialize app data (alloc mem, etc.)
// InitDeviceObjects() - To initialize the 3D scene objects
// FrameMove() - To animate the scene
// Render() - To render the scene
// DeleteDeviceObjects() - To cleanup the 3D scene objects
// FinalCleanup() - To cleanup app data (for exitting the app)
// MsgProc() - To handle Windows messages
//-----------------------------------------------------------------------------
class CD3DApplication
{
protected:
// Internal variables for the state of the app
D3DAdapterInfo m_Adapters[10];
DWORD m_dwNumAdapters;
DWORD m_dwAdapter;
BOOL m_bWindowed;
BOOL m_bActive;
BOOL m_bReady;
BOOL m_bHasFocus;
// Internal variables used for timing
BOOL m_bFrameMoving;
BOOL m_bSingleStep;
// Internal error handling function
HRESULT DisplayErrorMsg( HRESULT hr, DWORD dwType );
// Internal functions to manage and render the 3D scene
HRESULT BuildDeviceList();
BOOL FindDepthStencilFormat( UINT iAdapter, D3DDEVTYPE DeviceType,
D3DFORMAT TargetFormat, D3DFORMAT* pDepthStencilFormat );
HRESULT Initialize3DEnvironment();
HRESULT Resize3DEnvironment();
HRESULT ToggleFullscreen();
HRESULT ForceWindowed();
HRESULT UserSelectNewDevice();
VOID Cleanup3DEnvironment();
HRESULT Render3DEnvironment();
virtual HRESULT AdjustWindowForChange();
static INT_PTR CALLBACK SelectDeviceProc( HWND hDlg, UINT msg,
WPARAM wParam, LPARAM lParam );
protected:
// Main objects used for creating and rendering the 3D scene
D3DPRESENT_PARAMETERS m_d3dpp; // Parameters for CreateDevice/Reset
HWND m_hWnd; // The main app window
HWND m_hWndFocus; // The D3D focus window (usually same as m_hWnd)
HMENU m_hMenu; // App menu bar (stored here when fullscreen)
LPDIRECT3D8 m_pD3D; // The main D3D object
LPDIRECT3DDEVICE8 m_pd3dDevice; // The D3D rendering device
D3DCAPS8 m_d3dCaps; // Caps for the device
D3DSURFACE_DESC m_d3dsdBackBuffer; // Surface desc of the backbuffer
DWORD m_dwCreateFlags; // Indicate sw or hw vertex processing
DWORD m_dwWindowStyle; // Saved window style for mode switches
RECT m_rcWindowBounds; // Saved window bounds for mode switches
RECT m_rcWindowClient; // Saved client area size for mode switches
// Variables for timing
FLOAT m_fTime; // Current time in seconds
FLOAT m_fElapsedTime; // Time elapsed since last frame
FLOAT m_fFPS; // Instanteous frame rate
TCHAR m_strDeviceStats[90];// String to hold D3D device stats
TCHAR m_strFrameStats[90]; // String to hold frame stats
// Overridable variables for the app
TCHAR* m_strWindowTitle; // Title for the app's window
BOOL m_bUseDepthBuffer; // Whether to autocreate depthbuffer
DWORD m_dwMinDepthBits; // Minimum number of bits needed in depth buffer
DWORD m_dwMinStencilBits; // Minimum number of bits needed in stencil buffer
DWORD m_dwCreationWidth; // Width used to create window
DWORD m_dwCreationHeight; // Height used to create window
BOOL m_bShowCursorWhenFullscreen; // Whether to show cursor when fullscreen
BOOL m_bClipCursorWhenFullscreen; // Whether to limit cursor pos when fullscreen
// Overridable functions for the 3D scene created by the app
virtual HRESULT ConfirmDevice(D3DCAPS8*,DWORD,D3DFORMAT) { return S_OK; }
virtual HRESULT OneTimeSceneInit() { return S_OK; }
virtual HRESULT InitDeviceObjects() { return S_OK; }
virtual HRESULT RestoreDeviceObjects() { return S_OK; }
virtual HRESULT FrameMove() { return S_OK; }
virtual HRESULT Render() { return S_OK; }
virtual HRESULT InvalidateDeviceObjects() { return S_OK; }
virtual HRESULT DeleteDeviceObjects() { return S_OK; }
virtual HRESULT FinalCleanup() { return S_OK; }
public:
// Functions to create, run, pause, and clean up the application
virtual HRESULT Create( HINSTANCE hInstance );
virtual INT Run();
virtual LRESULT MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam );
virtual VOID Pause( BOOL bPause );
// Internal constructor
CD3DApplication();
};
#endif

View File

@@ -0,0 +1,130 @@
//-----------------------------------------------------------------------------
// File: D3DFile.h
//
// Desc: Support code for loading DirectX .X files.
//
// Copyright (c) 1997-2001 Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#ifndef D3DFILE_H
#define D3DFILE_H
#include <tchar.h>
#include <d3d8.h>
#include <d3dx8.h>
//-----------------------------------------------------------------------------
// Name: class CD3DMesh
// Desc: Class for loading and rendering file-based meshes
//-----------------------------------------------------------------------------
class CD3DMesh
{
public:
TCHAR m_strName[512];
LPD3DXMESH m_pSysMemMesh; // SysMem mesh, lives through resize
LPD3DXMESH m_pLocalMesh; // Local mesh, rebuilt on resize
DWORD m_dwNumMaterials; // Materials for the mesh
D3DMATERIAL8* m_pMaterials;
LPDIRECT3DTEXTURE8* m_pTextures;
BOOL m_bUseMaterials;
public:
// Rendering
HRESULT Render( LPDIRECT3DDEVICE8 pd3dDevice,
BOOL bDrawOpaqueSubsets = TRUE,
BOOL bDrawAlphaSubsets = TRUE );
// Mesh access
LPD3DXMESH GetSysMemMesh() { return m_pSysMemMesh; }
LPD3DXMESH GetLocalMesh() { return m_pLocalMesh; }
// Rendering options
VOID UseMeshMaterials( BOOL bFlag ) { m_bUseMaterials = bFlag; }
HRESULT SetFVF( LPDIRECT3DDEVICE8 pd3dDevice, DWORD dwFVF );
// Initializing
HRESULT RestoreDeviceObjects( LPDIRECT3DDEVICE8 pd3dDevice );
HRESULT InvalidateDeviceObjects();
// Creation/destruction
HRESULT Create( LPDIRECT3DDEVICE8 pd3dDevice, TCHAR* strFilename );
HRESULT Create( LPDIRECT3DDEVICE8 pd3dDevice, LPDIRECTXFILEDATA pFileData );
HRESULT Destroy();
CD3DMesh( TCHAR* strName = _T("CD3DFile_Mesh") );
virtual ~CD3DMesh();
};
//-----------------------------------------------------------------------------
// Name: class CD3DFrame
// Desc: Class for loading and rendering file-based meshes
//-----------------------------------------------------------------------------
class CD3DFrame
{
public:
TCHAR m_strName[512];
D3DXMATRIX m_mat;
CD3DMesh* m_pMesh;
TCHAR m_strMeshName[512];
CD3DFrame* m_pNext;
CD3DFrame* m_pChild;
public:
// Matrix access
VOID SetMatrix( D3DXMATRIX* pmat ) { m_mat = *pmat; }
D3DXMATRIX* GetMatrix() { return &m_mat; }
CD3DMesh* FindMesh( TCHAR* strMeshName );
CD3DFrame* FindFrame( TCHAR* strFrameName );
BOOL EnumMeshes( BOOL (*EnumMeshCB)(CD3DMesh*,VOID*),
VOID* pContext );
HRESULT Destroy();
HRESULT RestoreDeviceObjects( LPDIRECT3DDEVICE8 pd3dDevice );
HRESULT InvalidateDeviceObjects();
HRESULT Render( LPDIRECT3DDEVICE8 pd3dDevice,
BOOL bDrawOpaqueSubsets = TRUE,
BOOL bDrawAlphaSubsets = TRUE,
D3DXMATRIX* pmatWorldMartix = NULL);
CD3DFrame( TCHAR* strName = _T("CD3DFile_Frame") );
virtual ~CD3DFrame();
};
//-----------------------------------------------------------------------------
// Name: class CD3DFile
// Desc: Class for loading and rendering file-based meshes
//-----------------------------------------------------------------------------
class CD3DFile : public CD3DFrame
{
HRESULT LoadMesh( LPDIRECT3DDEVICE8 pd3dDevice, LPDIRECTXFILEDATA pFileData,
CD3DFrame* pParentFrame );
HRESULT LoadFrame( LPDIRECT3DDEVICE8 pd3dDevice, LPDIRECTXFILEDATA pFileData,
CD3DFrame* pParentFrame );
public:
HRESULT Create( LPDIRECT3DDEVICE8 pd3dDevice, TCHAR* strFilename );
HRESULT CreateFromResource( LPDIRECT3DDEVICE8 pd3dDevice, TCHAR* strResource, TCHAR* strType );
// For pure devices, specify the world transform. If the world transform is not
// specified on pure devices, this function will fail.
HRESULT Render( LPDIRECT3DDEVICE8 pd3dDevice, D3DXMATRIX* pmatWorldMatrix = NULL );
CD3DFile() : CD3DFrame( _T("CD3DFile_Root") ) {}
};
#endif

View File

@@ -0,0 +1,77 @@
//-----------------------------------------------------------------------------
// File: D3DFont.h
//
// Desc: Texture-based font class
//
// Copyright (c) 1999-2001 Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#ifndef D3DFONT_H
#define D3DFONT_H
#include <tchar.h>
#include <D3D8.h>
// Font creation flags
#define D3DFONT_BOLD 0x0001
#define D3DFONT_ITALIC 0x0002
#define D3DFONT_ZENABLE 0x0004
// Font rendering flags
#define D3DFONT_CENTERED 0x0001
#define D3DFONT_TWOSIDED 0x0002
#define D3DFONT_FILTERED 0x0004
//-----------------------------------------------------------------------------
// Name: class CD3DFont
// Desc: Texture-based font class for doing text in a 3D scene.
//-----------------------------------------------------------------------------
class CD3DFont
{
TCHAR m_strFontName[80]; // Font properties
DWORD m_dwFontHeight;
DWORD m_dwFontFlags;
LPDIRECT3DDEVICE8 m_pd3dDevice; // A D3DDevice used for rendering
LPDIRECT3DTEXTURE8 m_pTexture; // The d3d texture for this font
LPDIRECT3DVERTEXBUFFER8 m_pVB; // VertexBuffer for rendering text
DWORD m_dwTexWidth; // Texture dimensions
DWORD m_dwTexHeight;
FLOAT m_fTextScale;
FLOAT m_fTexCoords[128-32][4];
// Stateblocks for setting and restoring render states
DWORD m_dwSavedStateBlock;
DWORD m_dwDrawTextStateBlock;
public:
// 2D and 3D text drawing functions
HRESULT DrawText( FLOAT x, FLOAT y, DWORD dwColor,
TCHAR* strText, DWORD dwFlags=0L );
HRESULT DrawTextScaled( FLOAT x, FLOAT y, FLOAT z,
FLOAT fXScale, FLOAT fYScale, DWORD dwColor,
TCHAR* strText, DWORD dwFlags=0L );
HRESULT Render3DText( TCHAR* strText, DWORD dwFlags=0L );
// Function to get extent of text
HRESULT GetTextExtent( TCHAR* strText, SIZE* pSize );
// Initializing and destroying device-dependent objects
HRESULT InitDeviceObjects( LPDIRECT3DDEVICE8 pd3dDevice );
HRESULT RestoreDeviceObjects();
HRESULT InvalidateDeviceObjects();
HRESULT DeleteDeviceObjects();
// Constructor / destructor
CD3DFont( TCHAR* strFontName, DWORD dwHeight, DWORD dwFlags=0L );
~CD3DFont();
};
#endif

View File

@@ -0,0 +1,34 @@
//-----------------------------------------------------------------------------
// File: D3DRes.h
//
// Desc: Resource definitions required by the CD3DApplication class.
// Any application using the CD3DApplication class must include resources
// with the following identifiers.
//
// Copyright (c) 1999-2001 Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#ifndef D3DRES_H
#define D3DRES_H
#define IDI_MAIN_ICON 101 // Application icon
#define IDR_MAIN_ACCEL 113 // Keyboard accelerator
#define IDR_MENU 141 // Application menu
#define IDR_POPUP 142 // Popup menu
#define IDD_SELECTDEVICE 144 // "Change Device" dialog box
#define IDC_ADAPTER_COMBO 1002 // Adapter combobox for "SelectDevice" dlg
#define IDC_DEVICE_COMBO 1000 // Device combobox for "SelectDevice" dlg
#define IDC_FULLSCREENMODES_COMBO 1003 // Mode combobox for "SelectDevice" dlg
#define IDC_MULTISAMPLE_COMBO 1005 // MultiSample combobox for "SelectDevice" dlg
#define IDC_WINDOW 1016 // Radio button for windowed-mode
#define IDC_FULLSCREEN 1018 // Radio button for fullscreen-mode
#define IDM_CHANGEDEVICE 40002 // Command to invoke "Change Device" dlg
#define IDM_TOGGLEFULLSCREEN 40003 // Command to toggle fullscreen mode
#define IDM_TOGGLESTART 40004 // Command to toggle frame animation
#define IDM_SINGLESTEP 40005 // Command to single step frame animation
#define IDM_EXIT 40006 // Command to exit the application
#endif // D3DRES_H

View File

@@ -0,0 +1,314 @@
//-----------------------------------------------------------------------------
// File: D3DSaver.h
//
// Desc: Framework for screensavers that use Direct3D 8.0.
//
// Copyright (c) 2000 Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#ifndef _D3DSAVER_H
#define _D3DSAVER_H
//-----------------------------------------------------------------------------
// Error codes
//-----------------------------------------------------------------------------
enum APPMSGTYPE { MSG_NONE, MSGERR_APPMUSTEXIT, MSGWARN_SWITCHEDTOREF };
#define D3DAPPERR_NODIRECT3D 0x82000001
#define D3DAPPERR_NOWINDOW 0x82000002
#define D3DAPPERR_NOCOMPATIBLEDEVICES 0x82000003
#define D3DAPPERR_NOWINDOWABLEDEVICES 0x82000004
#define D3DAPPERR_NOHARDWAREDEVICE 0x82000005
#define D3DAPPERR_HALNOTCOMPATIBLE 0x82000006
#define D3DAPPERR_NOWINDOWEDHAL 0x82000007
#define D3DAPPERR_NODESKTOPHAL 0x82000008
#define D3DAPPERR_NOHALTHISMODE 0x82000009
#define D3DAPPERR_NONZEROREFCOUNT 0x8200000a
#define D3DAPPERR_MEDIANOTFOUND 0x8200000b
#define D3DAPPERR_RESIZEFAILED 0x8200000c
#define D3DAPPERR_INITDEVICEOBJECTSFAILED 0x8200000d
#define D3DAPPERR_CREATEDEVICEFAILED 0x8200000e
#define D3DAPPERR_NOPREVIEW 0x8200000f
//-----------------------------------------------------------------------------
// Constants
//-----------------------------------------------------------------------------
#define MAX_DISPLAYS 9
#define NO_ADAPTER 0xffffffff
#define NO_MONITOR 0xffffffff
//***************************************************************************************
// Modes of operation for screensaver
enum SaverMode
{
sm_config, // Config dialog box
sm_preview, // Mini preview window in Display Properties dialog
sm_full, // Full-on screensaver mode
sm_test, // Test mode
sm_passwordchange // Change password
};
// Prototype for VerifyScreenSavePwd() in password.cpl, used on Win9x
typedef BOOL (PASCAL * VERIFYPWDPROC) (HWND);
//-----------------------------------------------------------------------------
// Name: struct D3DModeInfo
// Desc: Structure for holding information about a display mode
//-----------------------------------------------------------------------------
struct D3DModeInfo
{
DWORD Width; // Screen width in this mode
DWORD Height; // Screen height in this mode
D3DFORMAT Format; // Pixel format in this mode
DWORD dwBehavior; // Hardware / Software / Mixed vertex processing
D3DFORMAT DepthStencilFormat; // Which depth/stencil format to use with this mode
};
//-----------------------------------------------------------------------------
// Name: struct D3DWindowedModeInfo
// Desc: Structure for holding information about a display mode
//-----------------------------------------------------------------------------
struct D3DWindowedModeInfo
{
D3DFORMAT DisplayFormat;
D3DFORMAT BackBufferFormat;
DWORD dwBehavior; // Hardware / Software / Mixed vertex processing
D3DFORMAT DepthStencilFormat; // Which depth/stencil format to use with this mode
};
//-----------------------------------------------------------------------------
// Name: struct D3DDeviceInfo
// Desc: Structure for holding information about a Direct3D device, including
// a list of modes compatible with this device
//-----------------------------------------------------------------------------
struct D3DDeviceInfo
{
// Device data
D3DDEVTYPE DeviceType; // Reference, HAL, etc.
D3DCAPS8 d3dCaps; // Capabilities of this device
const TCHAR* strDesc; // Name of this device
BOOL bCanDoWindowed; // Whether this device can work in windowed mode
// Modes for this device
DWORD dwNumModes;
D3DModeInfo modes[150];
// Current state
DWORD dwCurrentMode;
BOOL bWindowed;
D3DMULTISAMPLE_TYPE MultiSampleType;
};
//-----------------------------------------------------------------------------
// Name: struct D3DAdapterInfo
// Desc: Structure for holding information about an adapter, including a list
// of devices available on this adapter
//-----------------------------------------------------------------------------
struct D3DAdapterInfo
{
// Adapter data
DWORD iMonitor; // Which MonitorInfo corresponds to this adapter
D3DADAPTER_IDENTIFIER8 d3dAdapterIdentifier;
D3DDISPLAYMODE d3ddmDesktop; // Desktop display mode for this adapter
// Devices for this adapter
DWORD dwNumDevices;
D3DDeviceInfo devices[3];
BOOL bHasHAL;
BOOL bHasAppCompatHAL;
BOOL bHasSW;
BOOL bHasAppCompatSW;
// User's preferred mode settings for this adapter
DWORD dwUserPrefWidth;
DWORD dwUserPrefHeight;
D3DFORMAT d3dfmtUserPrefFormat;
BOOL bLeaveBlack; // If TRUE, don't render to this display
BOOL bDisableHW; // If TRUE, don't use HAL on this display
// Current state
DWORD dwCurrentDevice;
HWND hWndDevice;
};
//-----------------------------------------------------------------------------
// Name: struct MonitorInfo
// Desc: Structure for holding information about a monitor
//-----------------------------------------------------------------------------
struct MonitorInfo
{
TCHAR strDeviceName[128];
TCHAR strMonitorName[128];
HMONITOR hMonitor;
RECT rcScreen;
DWORD iAdapter; // Which D3DAdapterInfo corresponds to this monitor
HWND hWnd;
// Error message state
FLOAT xError;
FLOAT yError;
FLOAT widthError;
FLOAT heightError;
FLOAT xVelError;
FLOAT yVelError;
};
//-----------------------------------------------------------------------------
// Name: struct RenderUnit
// Desc:
//-----------------------------------------------------------------------------
struct RenderUnit
{
UINT iAdapter;
UINT iMonitor;
D3DDEVTYPE DeviceType; // Reference, HAL, etc.
DWORD dwBehavior;
IDirect3DDevice8* pd3dDevice;
D3DPRESENT_PARAMETERS d3dpp;
BOOL bDeviceObjectsInited; // InitDeviceObjects was called
BOOL bDeviceObjectsRestored; // RestoreDeviceObjects was called
TCHAR strDeviceStats[90];// String to hold D3D device stats
TCHAR strFrameStats[40]; // String to hold frame stats
};
//-----------------------------------------------------------------------------
// Name: class CD3DScreensaver
// Desc: D3D screensaver class
//-----------------------------------------------------------------------------
class CD3DScreensaver
{
public:
CD3DScreensaver();
virtual HRESULT Create( HINSTANCE hInstance );
virtual INT Run();
HRESULT DisplayErrorMsg( HRESULT hr, DWORD dwType = 0 );
protected:
SaverMode ParseCommandLine( TCHAR* pstrCommandLine );
VOID ChangePassword();
HRESULT DoSaver();
virtual VOID DoConfig() { }
virtual VOID ReadSettings() {};
VOID ReadScreenSettings( HKEY hkeyParent );
VOID WriteScreenSettings( HKEY hkeyParent );
virtual VOID DoPaint( HWND hwnd, HDC hdc );
HRESULT Initialize3DEnvironment();
VOID Cleanup3DEnvironment();
HRESULT Render3DEnvironment();
static LRESULT CALLBACK SaverProcStub( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam );
virtual LRESULT SaverProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam );
VOID InterruptSaver();
VOID ShutdownSaver();
VOID DoScreenSettingsDialog( HWND hwndParent );
static INT_PTR CALLBACK ScreenSettingsDlgProcStub( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam );
INT_PTR ScreenSettingsDlgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam );
VOID SetupAdapterPage(HWND hWnd);
HRESULT CreateSaverWindow();
HRESULT BuildDeviceList();
BOOL FindDepthStencilFormat( UINT iAdapter, D3DDEVTYPE DeviceType,
D3DFORMAT TargetFormat, D3DFORMAT* pDepthStencilFormat );
HRESULT CheckWindowedFormat( UINT iAdapter, D3DWindowedModeInfo* pD3DWindowedModeInfo );
HRESULT CreateFullscreenRenderUnit( RenderUnit* pRenderUnit );
HRESULT CreateWindowedRenderUnit( RenderUnit* pRenderUnit );
BOOL FindNextLowerMode( D3DDeviceInfo* pD3DDeviceInfo );
VOID SwitchToRenderUnit( UINT iRenderUnit );
VOID BuildProjectionMatrix( FLOAT fNear, FLOAT fFar, D3DXMATRIX* pMatrix );
HRESULT SetProjectionMatrix( FLOAT fNear, FLOAT fFar );
virtual VOID UpdateDeviceStats();
virtual VOID UpdateFrameStats();
virtual BOOL GetTextForError( HRESULT hr, TCHAR* pszError, DWORD dwNumChars );
VOID UpdateErrorBox();
VOID EnumMonitors( VOID );
BOOL GetBestAdapter( DWORD* piAdapter );
virtual VOID SetDevice( UINT iDevice ) { }
virtual HRESULT RegisterSoftwareDevice() { return S_OK; }
virtual HRESULT ConfirmDevice(D3DCAPS8* pCaps, DWORD dwBehavior,
D3DFORMAT fmtBackBuffer) { return S_OK; }
virtual HRESULT ConfirmMode( LPDIRECT3DDEVICE8 pd3dDev ) { return S_OK; }
virtual HRESULT OneTimeSceneInit() { return S_OK; }
virtual HRESULT InitDeviceObjects() { return S_OK; }
virtual HRESULT RestoreDeviceObjects() { return S_OK; }
virtual HRESULT FrameMove() { return S_OK; }
virtual HRESULT Render() { return S_OK; }
virtual HRESULT InvalidateDeviceObjects() { return S_OK; }
virtual HRESULT DeleteDeviceObjects() { return S_OK; }
virtual HRESULT FinalCleanup() { return S_OK; }
protected:
SaverMode m_SaverMode; // sm_config, sm_full, sm_preview, etc.
BOOL m_bAllScreensSame; // If TRUE, show same image on all screens
HWND m_hWnd; // Focus window and device window on primary
HWND m_hWndParent;
HINSTANCE m_hInstance;
BOOL m_bWaitForInputIdle; // Used to pause when preview starts
DWORD m_dwSaverMouseMoveCount;
BOOL m_bIs9x;
HINSTANCE m_hPasswordDLL;
VERIFYPWDPROC m_VerifySaverPassword;
BOOL m_bCheckingSaverPassword;
BOOL m_bWindowed;
// Variables for non-fatal error management
BOOL m_bErrorMode; // Whether to display an error
HRESULT m_hrError; // Error code to display
TCHAR m_szError[400]; // Error message text
MonitorInfo m_Monitors[MAX_DISPLAYS];
DWORD m_dwNumMonitors;
RenderUnit m_RenderUnits[MAX_DISPLAYS];
DWORD m_dwNumRenderUnits;
D3DAdapterInfo* m_Adapters[MAX_DISPLAYS];
DWORD m_dwNumAdapters;
IDirect3D8* m_pD3D;
IDirect3DDevice8* m_pd3dDevice; // Current D3D device
RECT m_rcRenderTotal; // Rect of entire area to be rendered
RECT m_rcRenderCurDevice; // Rect of render area of current device
D3DSURFACE_DESC m_d3dsdBackBuffer; // Info on back buffer for current device
TCHAR m_strWindowTitle[200]; // Title for the app's window
BOOL m_bAllowRef; // Whether to allow REF D3D device
BOOL m_bUseDepthBuffer; // Whether to autocreate depthbuffer
BOOL m_bMultithreaded; // Whether to make D3D thread-safe
BOOL m_bOneScreenOnly; // Only ever show screensaver on one screen
TCHAR m_strRegPath[200]; // Where to store registry info
DWORD m_dwMinDepthBits; // Minimum number of bits needed in depth buffer
DWORD m_dwMinStencilBits; // Minimum number of bits needed in stencil buffer
D3DSWAPEFFECT m_SwapEffectFullscreen; // SwapEffect to use in fullscreen Present()
D3DSWAPEFFECT m_SwapEffectWindowed; // SwapEffect to use in windowed Present()
// Variables for timing
FLOAT m_fTime; // Current time in seconds
FLOAT m_fElapsedTime; // Time elapsed since last frame
FLOAT m_fFPS; // Instanteous frame rate
TCHAR m_strDeviceStats[90];// D3D device stats for current device
TCHAR m_strFrameStats[40]; // Frame stats for current device
};
#endif

View File

@@ -0,0 +1,256 @@
//-----------------------------------------------------------------------------
// File: D3DUtil.h
//
// Desc: Helper functions and typing shortcuts for Direct3D programming.
//
// Copyright (c) 1997-2001 Microsoft Corporation. All rights reserved
//-----------------------------------------------------------------------------
#ifndef D3DUTIL_H
#define D3DUTIL_H
#include <D3D8.h>
#include <D3DX8Math.h>
//-----------------------------------------------------------------------------
// Name: D3DUtil_InitMaterial()
// Desc: Initializes a D3DMATERIAL8 structure, setting the diffuse and ambient
// colors. It does not set emissive or specular colors.
//-----------------------------------------------------------------------------
VOID D3DUtil_InitMaterial( D3DMATERIAL8& mtrl, FLOAT r=0.0f, FLOAT g=0.0f,
FLOAT b=0.0f, FLOAT a=1.0f );
//-----------------------------------------------------------------------------
// Name: D3DUtil_InitLight()
// Desc: Initializes a D3DLIGHT structure, setting the light position. The
// diffuse color is set to white, specular and ambient left as black.
//-----------------------------------------------------------------------------
VOID D3DUtil_InitLight( D3DLIGHT8& light, D3DLIGHTTYPE ltType,
FLOAT x=0.0f, FLOAT y=0.0f, FLOAT z=0.0f );
//-----------------------------------------------------------------------------
// Name: D3DUtil_CreateTexture()
// Desc: Helper function to create a texture. It checks the root path first,
// then tries the DXSDK media path (as specified in the system registry).
//-----------------------------------------------------------------------------
HRESULT D3DUtil_CreateTexture( LPDIRECT3DDEVICE8 pd3dDevice, TCHAR* strTexture,
LPDIRECT3DTEXTURE8* ppTexture,
D3DFORMAT d3dFormat = D3DFMT_UNKNOWN );
//-----------------------------------------------------------------------------
// Name: D3DUtil_SetColorKey()
// Desc: Changes all texels matching the colorkey to transparent, black.
//-----------------------------------------------------------------------------
HRESULT D3DUtil_SetColorKey( LPDIRECT3DTEXTURE8 pTexture, DWORD dwColorKey );
//-----------------------------------------------------------------------------
// Name: D3DUtil_CreateVertexShader()
// Desc: Assembles and creates a file-based vertex shader
//-----------------------------------------------------------------------------
HRESULT D3DUtil_CreateVertexShader( LPDIRECT3DDEVICE8 pd3dDevice,
TCHAR* strFilename, DWORD* pdwVertexDecl,
DWORD* pdwVertexShader );
//-----------------------------------------------------------------------------
// Name: D3DUtil_GetCubeMapViewMatrix()
// Desc: Returns a view matrix for rendering to a face of a cubemap.
//-----------------------------------------------------------------------------
D3DXMATRIX D3DUtil_GetCubeMapViewMatrix( DWORD dwFace );
//-----------------------------------------------------------------------------
// Name: D3DUtil_GetRotationFromCursor()
// Desc: Returns a quaternion for the rotation implied by the window's cursor
// position.
//-----------------------------------------------------------------------------
D3DXQUATERNION D3DUtil_GetRotationFromCursor( HWND hWnd,
FLOAT fTrackBallRadius=1.0f );
//-----------------------------------------------------------------------------
// Name: D3DUtil_SetDeviceCursor
// Desc: Builds and sets a cursor for the D3D device based on hCursor.
//-----------------------------------------------------------------------------
HRESULT D3DUtil_SetDeviceCursor( LPDIRECT3DDEVICE8 pd3dDevice, HCURSOR hCursor,
BOOL bAddWatermark );
//-----------------------------------------------------------------------------
// Name: class CD3DArcBall
// Desc:
//-----------------------------------------------------------------------------
class CD3DArcBall
{
INT m_iWidth; // ArcBall's window width
INT m_iHeight; // ArcBall's window height
FLOAT m_fRadius; // ArcBall's radius in screen coords
FLOAT m_fRadiusTranslation; // ArcBall's radius for translating the target
D3DXQUATERNION m_qDown; // Quaternion before button down
D3DXQUATERNION m_qNow; // Composite quaternion for current drag
D3DXMATRIX m_matRotation; // Matrix for arcball's orientation
D3DXMATRIX m_matRotationDelta; // Matrix for arcball's orientation
D3DXMATRIX m_matTranslation; // Matrix for arcball's position
D3DXMATRIX m_matTranslationDelta; // Matrix for arcball's position
BOOL m_bDrag; // Whether user is dragging arcball
BOOL m_bRightHanded; // Whether to use RH coordinate system
D3DXVECTOR3 ScreenToVector( int sx, int sy );
public:
LRESULT HandleMouseMessages( HWND, UINT, WPARAM, LPARAM );
D3DXMATRIX* GetRotationMatrix() { return &m_matRotation; }
D3DXMATRIX* GetRotationDeltaMatrix() { return &m_matRotationDelta; }
D3DXMATRIX* GetTranslationMatrix() { return &m_matTranslation; }
D3DXMATRIX* GetTranslationDeltaMatrix() { return &m_matTranslationDelta; }
BOOL IsBeingDragged() { return m_bDrag; }
VOID SetRadius( FLOAT fRadius );
VOID SetWindow( INT w, INT h, FLOAT r=0.9 );
VOID SetRightHanded( BOOL bRightHanded ) { m_bRightHanded = bRightHanded; }
CD3DArcBall();
};
//-----------------------------------------------------------------------------
// Name: class CD3DCamera
// Desc:
//-----------------------------------------------------------------------------
class CD3DCamera
{
D3DXVECTOR3 m_vEyePt; // Attributes for view matrix
D3DXVECTOR3 m_vLookatPt;
D3DXVECTOR3 m_vUpVec;
D3DXVECTOR3 m_vView;
D3DXVECTOR3 m_vCross;
D3DXMATRIX m_matView;
D3DXMATRIX m_matBillboard; // Special matrix for billboarding effects
FLOAT m_fFOV; // Attributes for projection matrix
FLOAT m_fAspect;
FLOAT m_fNearPlane;
FLOAT m_fFarPlane;
D3DXMATRIX m_matProj;
public:
// Access functions
D3DXVECTOR3 GetEyePt() { return m_vEyePt; }
D3DXVECTOR3 GetLookatPt() { return m_vLookatPt; }
D3DXVECTOR3 GetUpVec() { return m_vUpVec; }
D3DXVECTOR3 GetViewDir() { return m_vView; }
D3DXVECTOR3 GetCross() { return m_vCross; }
D3DXMATRIX GetViewMatrix() { return m_matView; }
D3DXMATRIX GetBillboardMatrix() { return m_matBillboard; }
D3DXMATRIX GetProjMatrix() { return m_matProj; }
VOID SetViewParams( D3DXVECTOR3 &vEyePt, D3DXVECTOR3& vLookatPt,
D3DXVECTOR3& vUpVec );
VOID SetProjParams( FLOAT fFOV, FLOAT fAspect, FLOAT fNearPlane,
FLOAT fFarPlane );
CD3DCamera();
};
//-----------------------------------------------------------------------------
// Helper macros for pixel shader instructions
//-----------------------------------------------------------------------------
// Parameter writemasks
#define D3DPSP_WRITEMASK_B D3DSP_WRITEMASK_0
#define D3DPSP_WRITEMASK_G D3DSP_WRITEMASK_1
#define D3DPSP_WRITEMASK_R D3DSP_WRITEMASK_2
#define D3DPSP_WRITEMASK_A D3DSP_WRITEMASK_3
#define D3DPSP_WRITEMASK_C (D3DPSP_WRITEMASK_B|D3DPSP_WRITEMASK_G|D3DPSP_WRITEMASK_R)
#define D3DPSP_WRITEMASK_ALL (D3DSP_WRITEMASK_0|D3DSP_WRITEMASK_1|D3DSP_WRITEMASK_2|D3DSP_WRITEMASK_3)
#define D3DPSP_WRITEMASK_10 (D3DSP_WRITEMASK_0|D3DSP_WRITEMASK_1)
#define D3DPSP_WRITEMASK_32 (D3DSP_WRITEMASK_2|D3DSP_WRITEMASK_3)
// Source and destination parameter token
#define D3DPS_REGNUM_MASK(_Num) ( (1L<<31) | ((_Num)&D3DSP_REGNUM_MASK) )
#define D3DPS_DST(_Num) ( D3DPS_REGNUM_MASK(_Num) | D3DSPR_TEMP | D3DPSP_WRITEMASK_ALL )
#define D3DPS_SRC_TEMP(_Num) ( D3DPS_REGNUM_MASK(_Num) | D3DSP_NOSWIZZLE | D3DSPR_TEMP )
#define D3DPS_SRC_INPUT(_Num) ( D3DPS_REGNUM_MASK(_Num) | D3DSP_NOSWIZZLE | D3DSPR_INPUT )
#define D3DPS_SRC_CONST(_Num) ( D3DPS_REGNUM_MASK(_Num) | D3DSP_NOSWIZZLE | D3DSPR_CONST )
#define D3DPS_SRC_TEXTURE(_Num) ( D3DPS_REGNUM_MASK(_Num) | D3DSP_NOSWIZZLE | D3DSPR_TEXTURE )
#define D3DVS_SRC_ADDR(_Num) ( D3DPS_REGNUM_MASK(_Num) | D3DSP_NOSWIZZLE | D3DSPR_ADDR )
#define D3DVS_SRC_RASTOUT(_Num) ( D3DPS_REGNUM_MASK(_Num) | D3DSP_NOSWIZZLE | D3DSPR_RASTOUT )
#define D3DVS_SRC_ATTROUT(_Num) ( D3DPS_REGNUM_MASK(_Num) | D3DSP_NOSWIZZLE | D3DSPR_ATTROUT )
#define D3DVS_SRC_TEXCRDOUT(_Num) ( D3DPS_REGNUM_MASK(_Num) | D3DSP_NOSWIZZLE | D3DSPR_TEXCRDOUT )
// Temp destination registers
#define D3DS_DR0 D3DPS_DST(0)
#define D3DS_DR1 D3DPS_DST(1)
#define D3DS_DR2 D3DPS_DST(2)
#define D3DS_DR3 D3DPS_DST(3)
#define D3DS_DR4 D3DPS_DST(4)
#define D3DS_DR5 D3DPS_DST(5)
#define D3DS_DR6 D3DPS_DST(6)
#define D3DS_DR7 D3DPS_DST(7)
// Temp source registers
#define D3DS_SR0 D3DPS_SRC_TEMP(0)
#define D3DS_SR1 D3DPS_SRC_TEMP(1)
#define D3DS_SR2 D3DPS_SRC_TEMP(2)
#define D3DS_SR3 D3DPS_SRC_TEMP(3)
#define D3DS_SR4 D3DPS_SRC_TEMP(4)
#define D3DS_SR5 D3DPS_SRC_TEMP(5)
#define D3DS_SR6 D3DPS_SRC_TEMP(6)
#define D3DS_SR7 D3DPS_SRC_TEMP(7)
// Texture parameters
#define D3DS_T0 D3DPS_SRC_TEXTURE(0)
#define D3DS_T1 D3DPS_SRC_TEXTURE(1)
#define D3DS_T2 D3DPS_SRC_TEXTURE(2)
#define D3DS_T3 D3DPS_SRC_TEXTURE(3)
#define D3DS_T4 D3DPS_SRC_TEXTURE(4)
#define D3DS_T5 D3DPS_SRC_TEXTURE(5)
#define D3DS_T6 D3DPS_SRC_TEXTURE(6)
#define D3DS_T7 D3DPS_SRC_TEXTURE(7)
// Constant (factor) source parameters
#define D3DS_C0 D3DPS_SRC_CONST(0)
#define D3DS_C1 D3DPS_SRC_CONST(1)
#define D3DS_C2 D3DPS_SRC_CONST(2)
#define D3DS_C3 D3DPS_SRC_CONST(3)
#define D3DS_C4 D3DPS_SRC_CONST(4)
#define D3DS_C5 D3DPS_SRC_CONST(5)
#define D3DS_C6 D3DPS_SRC_CONST(6)
#define D3DS_C7 D3DPS_SRC_CONST(7)
// Iterated source parameters (0==Diffuse, 1==specular)
#define D3DS_V0 D3DPS_SRC_INPUT(0)
#define D3DS_V1 D3DPS_SRC_INPUT(1)
#endif // D3DUTIL_H

View File

@@ -0,0 +1,140 @@
//-----------------------------------------------------------------------------
// File: ddutil.cpp
//
// Desc: Routines for loading bitmap and palettes from resources
//
// Copyright (C) 1998-2001 Microsoft Corporation. All Rights Reserved.
//-----------------------------------------------------------------------------
#ifndef DDUTIL_H
#define DDUTIL_H
#include <ddraw.h>
#include <d3d.h>
//-----------------------------------------------------------------------------
// Classes defined in this header file
//-----------------------------------------------------------------------------
class CDisplay;
class CSurface;
//-----------------------------------------------------------------------------
// Flags for the CDisplay and CSurface methods
//-----------------------------------------------------------------------------
#define DSURFACELOCK_READ
#define DSURFACELOCK_WRITE
//-----------------------------------------------------------------------------
// Name: class CDisplay
// Desc: Class to handle all DDraw aspects of a display, including creation of
// front and back buffers, creating offscreen surfaces and palettes,
// and blitting surface and displaying bitmaps.
//-----------------------------------------------------------------------------
class CDisplay
{
protected:
LPDIRECTDRAW7 m_pDD;
LPDIRECTDRAWSURFACE7 m_pddsFrontBuffer;
LPDIRECTDRAWSURFACE7 m_pddsBackBuffer;
LPDIRECTDRAWSURFACE7 m_pddsBackBufferLeft; // For stereo modes
HWND m_hWnd;
RECT m_rcWindow;
BOOL m_bWindowed;
BOOL m_bStereo;
public:
CDisplay();
~CDisplay();
// Access functions
HWND GetHWnd() { return m_hWnd; }
LPDIRECTDRAW7 GetDirectDraw() { return m_pDD; }
LPDIRECTDRAWSURFACE7 GetFrontBuffer() { return m_pddsFrontBuffer; }
LPDIRECTDRAWSURFACE7 GetBackBuffer() { return m_pddsBackBuffer; }
LPDIRECTDRAWSURFACE7 GetBackBufferLeft() { return m_pddsBackBufferLeft; }
// Status functions
BOOL IsWindowed() { return m_bWindowed; }
BOOL IsStereo() { return m_bStereo; }
// Creation/destruction methods
HRESULT CreateFullScreenDisplay( HWND hWnd, DWORD dwWidth, DWORD dwHeight,
DWORD dwBPP );
HRESULT CreateWindowedDisplay( HWND hWnd, DWORD dwWidth, DWORD dwHeight );
HRESULT InitClipper();
HRESULT UpdateBounds();
virtual HRESULT DestroyObjects();
// Methods to create child objects
HRESULT CreateSurface( CSurface** ppSurface, DWORD dwWidth,
DWORD dwHeight );
HRESULT CreateSurfaceFromBitmap( CSurface** ppSurface, TCHAR* strBMP,
DWORD dwDesiredWidth,
DWORD dwDesiredHeight );
HRESULT CreateSurfaceFromText( CSurface** ppSurface, HFONT hFont,
TCHAR* strText,
COLORREF crBackground,
COLORREF crForeground );
HRESULT CreatePaletteFromBitmap( LPDIRECTDRAWPALETTE* ppPalette, const TCHAR* strBMP );
// Display methods
HRESULT Clear( DWORD dwColor = 0L );
HRESULT ColorKeyBlt( DWORD x, DWORD y, LPDIRECTDRAWSURFACE7 pdds,
RECT* prc = NULL );
HRESULT Blt( DWORD x, DWORD y, LPDIRECTDRAWSURFACE7 pdds,
RECT* prc=NULL, DWORD dwFlags=0 );
HRESULT Blt( DWORD x, DWORD y, CSurface* pSurface, RECT* prc = NULL );
HRESULT ShowBitmap( HBITMAP hbm, LPDIRECTDRAWPALETTE pPalette=NULL );
HRESULT SetPalette( LPDIRECTDRAWPALETTE pPalette );
HRESULT Present();
};
//-----------------------------------------------------------------------------
// Name: class CSurface
// Desc: Class to handle aspects of a DirectDrawSurface.
//-----------------------------------------------------------------------------
class CSurface
{
LPDIRECTDRAWSURFACE7 m_pdds;
DDSURFACEDESC2 m_ddsd;
BOOL m_bColorKeyed;
public:
LPDIRECTDRAWSURFACE7 GetDDrawSurface() { return m_pdds; }
BOOL IsColorKeyed() { return m_bColorKeyed; }
HRESULT DrawBitmap( HBITMAP hBMP, DWORD dwBMPOriginX = 0, DWORD dwBMPOriginY = 0,
DWORD dwBMPWidth = 0, DWORD dwBMPHeight = 0 );
HRESULT DrawBitmap( TCHAR* strBMP, DWORD dwDesiredWidth, DWORD dwDesiredHeight );
HRESULT DrawText( HFONT hFont, TCHAR* strText, DWORD dwOriginX, DWORD dwOriginY,
COLORREF crBackground, COLORREF crForeground );
HRESULT SetColorKey( DWORD dwColorKey );
DWORD ConvertGDIColor( COLORREF dwGDIColor );
static HRESULT GetBitMaskInfo( DWORD dwBitMask, DWORD* pdwShift, DWORD* pdwBits );
HRESULT Create( LPDIRECTDRAW7 pDD, DDSURFACEDESC2* pddsd );
HRESULT Create( LPDIRECTDRAWSURFACE7 pdds );
HRESULT Destroy();
CSurface();
~CSurface();
};
#endif // DDUTIL_H

View File

@@ -0,0 +1,866 @@
//-----------------------------------------------------------------------------
// File: didcfgview.h
//
// Desc: Header file for DIDCfgView, a class that encapsulates a view of a
// DirectInput device. The DIDCfgView class exists to make it easier
// to make custom interfaces to view or configure action mappings for
// input devices(instead of using IDirectInput8::ConfigureDevices).
//
// To use the DIDCfgView class, you initialize it for a particular
// DirectInput device. You then set up state information for how the
// image should be drawn: colors, fonts, and details for callouts(the
// lines drawn from each axis/button to a label). Finally, you can
// call RenderView, passing in a bitmap or HDC for DIDCfgView to draw
// the image to.
//
// DIDCfgView is the only class in this file that you need to understand
// or interface to. The other classes shown here are only used to
// implement the DIDCfgView class.
//
//
// Copyright (c) 1999-2001 Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#ifndef __DIDCV_H__
#define __DIDCV_H__
#include <windows.h>
#include <dinput.h>
// invalid id, used for unique, signed identifiers
#define DIDCV_INVALID_ID -1
// flags for callout states
#define DIDCV_DRAWCALLOUT 0x1
#define DIDCV_DRAWOVERLAY 0x2
#define DIDCV_DRAWHIGHLIGHT 0x4
#define DIDCV_DRAWEMPTYCALLOUT 0x8
#define DIDCV_DRAWFULLNAME 0x10
// all flags set
#define DIDCV_ALL_CALLOUT_STATE_SET 0xFFFFFFFF
// default dimensions
#define DIDCV_MAX_IMAGE_WIDTH 512
#define DIDCV_MAX_IMAGE_HEIGHT 512
#define DIDCV_CUSTOM_VIEW_WIDTH 400
#define DIDCV_CUSTOM_VIEW_HEIGHT 300
// DidcvCreateFont attribute flags
#define DIDCV_FONT_BOLD 0x1
#define DIDCV_FONT_ITALIC 0x2
#define DIDCV_FONT_UNDERLINE 0x4
#define DIDCV_FONT_STRIKEOUT 0x8
// default font point width
#define DIDCV_DEFAULT_FONT_SIZE 90
// default size of callout array in DidcvCalloutManager
#define DIDCV_DEFAULT_CALLOUT_MANAGER_ARRAY_SIZE 0
// default size of callout array in DidcvCalloutSet
#define DIDCV_DEFAULT_CALLOUT_SET_ARRAY_SIZE 8
// forward declarations
class DidcvViewManager;
class DidcvCalloutManager;
class DidcvBitmap;
class DidcvCallout;
class DidcvCalloutSet;
struct DIDCfgViewInfo;
struct DidcvCalloutData;
struct DidcvCalloutState;
struct DidcvActionMap;
struct DidcvCustomViewInfo;
//-----------------------------------------------------------------------------
// Name: class DIDCfgView
// Desc: main interface for retrieving and rendering device configuration views
//
// Init() - initializes the object for a particular DirectInputDevice
// SetActionFormat() - sets the action mapping for the device
// SetCalloutState() - specifies state for a given callout
// SetAllCalloutState() - sets the state for all callouts
// GetObjectIDByLocation() - gets object id at location of current view
// SetCurrentView() - sets the current view to be rendered
// RebuildViews() - collapses or expand the views for this device
// RenderView() - renders device configuration view with image,
// callout information, action mapping.
//-----------------------------------------------------------------------------
class DIDCfgView
{
public:
DIDCfgView();
~DIDCfgView();
public:
// main device configuration view interface
HRESULT Init( LPDIRECTINPUTDEVICE8 pDevice );
HRESULT SetActionFormat( LPDIACTIONFORMAT pDiaf );
HRESULT SetCalloutState( DWORD dwFlags, DWORD dwObjID );
HRESULT SetAllCalloutState( DWORD dwFlags );
HRESULT GetObjectIDByLocation( LPDWORD pdwObjID, LPPOINT pPt );
HRESULT SetCurrentView( INT nView );
HRESULT RebuildViews( BOOL bCompact );
HRESULT RenderView( HBITMAP hBitmap, BOOL bIsDib );
HRESULT RenderView( HDC hdc );
// rendering options
HRESULT SetViewOrigin( const POINT* pPtOrg, POINT* pPtOldOrg );
HRESULT CalcCenterOrgForCurrentView( const SIZE* pImgSize, POINT* pPtOrg, BOOL bSetOrigin = FALSE );
VOID SetDefaultText( const TCHAR* pctszDefaultText, DWORD length );
VOID SetColors( COLORREF crFore, COLORREF crBack, COLORREF crHighlight, COLORREF crHighlightLine );
VOID GetColors( COLORREF* pCrFore, COLORREF* pCrBack, COLORREF* pCrHighlight, COLORREF* pCrHighlightLine );
HRESULT SetFont( const TCHAR* pctszFontName, DWORD dwAttributes );
HFONT GetFont();
// information access functios
HRESULT GetInfo( DIDCfgViewInfo* pCfgViewInfo );
HRESULT GetCurrentView( LPINT lpnView );
HRESULT GetCalloutState( LPDWORD lpdwFlags, DWORD dwObjID );
protected:
// protected helper functions
VOID CleanUp();
HRESULT InitAlloc();
HRESULT InitImageInfoRetrieve( LPDIRECTINPUTDEVICE8 pDevice );
HRESULT InitImageInfoProcess();
VOID CalcSizes( const DIDEVICEIMAGEINFO* prgImageInfoArray, DWORD dwNumElements, const LPDWORD pNumViews, LPDWORD pNumCallouts, LPDWORD pNumDistinctObjID );
HRESULT RenderView( HDC hdc, VOID* pBits, INT width, INT height );
HRESULT InitCustomViews( LPDIRECTINPUTDEVICE8 pDevice, BOOL bUseInternal = FALSE );
HRESULT BuildCustomViews();
VOID RenderFullname( HDC hdc, const TCHAR* pctszFullname, const RECT* pRect );
BOOL CopyActionMap( LPDIACTIONFORMAT pDiaf );
protected:
// data structures for managing views and callouts
DidcvViewManager* m_lpViewManager;
DidcvCalloutManager* m_lpCalloutManager;
// keeps track of whether this has been initialized
BOOL m_bIsInit;
// the index of the next view to render
INT m_nView;
// pointer to the DIDEVICEIMAGEINFOHEADER
LPDIDEVICEIMAGEINFOHEADER m_lpDidImgHeader;
// custom device view data
DidcvCustomViewInfo* m_lpCustomViewInfo;
// device reference
LPDIRECTINPUTDEVICE8 m_lpDIDevice;
// action mapping copy
LPDIACTIONFORMAT m_lpDiaf;
// can this view be collapsed
BOOL m_bCanBeCollapsed;
// is this view compacted
BOOL m_bIsCollapsed;
// rendering options
COLORREF m_crFore;
COLORREF m_crBack;
COLORREF m_crHighlight;
COLORREF m_crHighlightLine;
POINT m_ptOrigin;
HFONT m_hFont;
TCHAR m_tszDefaultText [MAX_PATH];
};
//-----------------------------------------------------------------------------
// Name: struct DIDCfgViewInfo
// Desc: struct containing current information about DIDCfgView states
//-----------------------------------------------------------------------------
struct DIDCfgViewInfo
{
BOOL bIsInit; // is the CfgView object initialized
INT iCurrentViewID; // the ID of the current view
INT iNumTotalViews; // total number of views
DWORD dwNumUniqueCallouts; // number of unique
BOOL bCanBeCollapsed; // can views for this CfgView object be compacted
BOOL bIsCollapsed; // is the CfgView currently using collapsed views
DIDCfgViewInfo()
: bIsInit( FALSE ),
iCurrentViewID( DIDCV_INVALID_ID ),
iNumTotalViews( 0 ),
dwNumUniqueCallouts( 0 ),
bCanBeCollapsed( FALSE ),
bIsCollapsed( FALSE )
{ }
};
//-----------------------------------------------------------------------------
// Name: struct DidcvCustomViewInfo
// Desc: object containing information about custom views
//-----------------------------------------------------------------------------
struct DidcvCustomViewInfo
{
DWORD dwType; // type of the operation(count or save)
DWORD dwCount; // the total count of items
DWORD dwSize; // number of items actually in array
LPDIDEVICEOBJECTINSTANCE* rgObjData; // array of control info
DidcvCustomViewInfo()
: dwType( 0 ),
dwCount( 0 ),
dwSize( 0 ),
rgObjData( NULL )
{ }
~DidcvCustomViewInfo() { CleanUp(); }
VOID CleanUp();
};
//-----------------------------------------------------------------------------
// Name: class DidcvView
// Desc: data structure for representing one view of a device
//-----------------------------------------------------------------------------
class DidcvView
{
public:
virtual ~DidcvView() { };
// DidcvView interface
void SetOffset( INT nOffset );
void SetID( INT nID );
INT GetOffset() const;
INT GetID() const;
// rendering
virtual BOOL GetViewSize( SIZE* pSize ) const = 0;
virtual void Render( HDC hdc, VOID* pBits, INT width, INT height, const POINT* pPtOrigin ) = 0;
protected:
// constructor
DidcvView();
// the original offset in the array returned by DirectInputDevice8::GetImage
INT m_nOffset;
// the internally assigned unique identifier
INT m_nID;
};
//-----------------------------------------------------------------------------
// Name: class DidcvBitmapView
// Desc: subclass of DidcvView that renders a bitmap
//-----------------------------------------------------------------------------
class DidcvBitmapView : public DidcvView
{
public:
~DidcvBitmapView();
// interface
virtual BOOL GetViewSize( SIZE* pSize ) const;
virtual void Render( HDC hdc, VOID* pBits, INT width, INT height, const POINT* pPtOrigin );
public:
// function to instantiate a DidcvBitmapView
static DidcvBitmapView* Create( LPCTSTR ptszImagePath, DWORD dwFlags );
private:
// constructor
DidcvBitmapView();
protected:
// bitmap of the view
DidcvBitmap* m_lpBitmap;
};
//-----------------------------------------------------------------------------
// Name: class DidcvCustomView
// Desc: subclass of DidcvView that renders a view from custom data
//-----------------------------------------------------------------------------
class DidcvCustomView : public DidcvView
{
public:
~DidcvCustomView() { }
// interface
virtual BOOL GetViewSize( SIZE* pSize ) const;
virtual void Render( HDC hdc, VOID* pBits, INT width, INT height, const POINT* pPtOrigin );
public:
// static function to instantiate a DidcvCustomView
static DidcvCustomView* Create( const DidcvCustomViewInfo* pInfo, DWORD dwStartIndex, DWORD* pFinishIndex );
static BOOL CalcImageInfo( DWORD index, LPRECT rcOverlay, LPDWORD pNumPoints, LPPOINT rgptCalloutLine, LPRECT rcCalloutRect );
static DWORD CalcNumViews( DWORD dwCount );
private:
// constructor
DidcvCustomView( const DidcvCustomViewInfo* pInfo, DWORD dwStartIndex, DWORD dwEndIndex );
protected:
// returns coordinates for a given index
void CalcCoordinates( DWORD dwIndex, LPRECT lpRect );
// custom data from which to render the view
const DidcvCustomViewInfo* m_lpCustomViewInfoRef;
DWORD m_dwStartIndex;
DWORD m_dwEndIndex;
};
//-----------------------------------------------------------------------------
// Name: class DidcvViewManager
// Desc: stores and manages all the views for particular device
//-----------------------------------------------------------------------------
class DidcvViewManager
{
public:
DidcvViewManager();
~DidcvViewManager();
// interface
BOOL SetCapacity( UINT uCapacity, BOOL bDeleteContent = TRUE );
BOOL AddImage( DidcvView* pView, INT nOffset = DIDCV_INVALID_ID );
DidcvView* GetImage( INT nID );
DidcvView* GetImageByOffset( INT nOffset );
UINT GetNumViews() const;
void CleanUp();
protected:
// table holding references to views, indexed by the internal unique identifier
DidcvView ** m_ppViewTable;
UINT m_capacity;
UINT m_size;
};
//-----------------------------------------------------------------------------
// Name: class DidcvCallout
// Desc: data structure for representing one callout on a particular view
// A callout is the line drawn from each axis/button to a label
//-----------------------------------------------------------------------------
class DidcvCallout
{
public:
~DidcvCallout();
// accessor functions to information retrieved from DirectInput
DWORD GetObjID() const;
const RECT & GetOverlayRect() const;
const RECT & GetCalloutRect() const;
const POINT* GetCalloutLine( DWORD* lpNumPts ) const;
DWORD GetTextAlign() const;
DWORD GetOverlayOffset() const;
// accessor functions to internal data
void SetAssociatedViewID( INT nViewRef );
INT GetAssociatedViewID() const;
void SetDataRef( const DidcvCalloutData* lpData );
const DidcvCalloutData* GetDataRef() const;
// hit test for a given point
DWORD HitTest( LPPOINT lpPt ) const;
// draw the overlay
DWORD DrawOverlay( HDC hDC, VOID* lpBits, INT width, INT height, const POINT* pptOrigin );
public:
// static functions to instantiate a callout object
static DidcvCallout* Create( LPDIDEVICEIMAGEINFO devImgInfo );
private:
// private constructor
DidcvCallout();
protected:
// copy of device information
DIDEVICEIMAGEINFO m_devImgInfo;
// the view that this particular callout is associated with
INT m_nViewRef;
// pointer to callout state/data
const DidcvCalloutData* m_lpDataRef;
// the bitmap of the overlay
DidcvBitmap* m_lpOverlayBitmap;
};
// default array size
#define GW_ARRAY_DEFAULT_SIZE 4
//-----------------------------------------------------------------------------
// Name: class GwArray
// Desc: templated c-style array class for PRIMITIVE data types only
//-----------------------------------------------------------------------------
template <class Item>
class GwArray
{
public:
// constructors
GwArray() { this->Alloc( GW_ARRAY_DEFAULT_SIZE ); m_size = 0; }
GwArray( UINT initCap ) { this->Alloc( initCap ); m_size = 0; }
~GwArray() { this->DeAlloc(); m_size = 0; }
public:
void SetSize( UINT newCap )
{
if( newCap == m_capacity )
return;
m_size =( newCap < m_size ? newCap : m_size );
UINT old_cap = m_capacity;
UINT numoverlap =( newCap > m_capacity ? m_capacity : newCap );
Item* oldList = m_list;
this->Alloc( newCap );
if( oldList )
{
memcpy( m_list, oldList, sizeof( Item )* numoverlap );
// free( oldList );
delete [] oldList;
}
}
Item & operator[]( UINT index )
{
if( index >= m_capacity )
assert( index >= 0 && index < m_capacity );
return m_list[index];
}
const Item & operator[]( UINT index ) const
{
if( index >= m_capacity )
assert( index >= 0 && index < m_capacity );
return m_list[index];
}
void PushBack( const Item & item )
{
if( m_capacity == 0 )
SetSize( 2 );
else if( m_size >= m_capacity )
SetSize( m_capacity* 2 );
m_list[m_size] = item;
m_size++;
}
void Resize( UINT newCap ) { SetSize( newCap ); }
void PopBack() { if( m_size ) m_size--; }
void Clear() { m_size = 0; }
void Trim() { Resize( m_size ); }
UINT Capacity() const { return m_capacity; }
UINT Size() const { return m_size; }
protected:
inline void Alloc( UINT cap )
{
if( cap == 0 )
m_list = NULL;
else
{
m_list = new Item[cap];
assert( m_list );
memset( m_list, 0, sizeof( Item )* cap );
}
m_capacity = cap;
}
inline void DeAlloc()
{
if( m_list != NULL )
{
//free( m_list );
delete [] m_list;
m_list = NULL;
}
m_capacity = 0;
}
protected:
// array
Item* m_list;
// number of entries the array can hold
UINT m_capacity;
// number of entries added using PushBack() minus # removed using PopBack()
UINT m_size;
};
//-----------------------------------------------------------------------------
// Name: class DidcvCalloutApplicant
// Desc: abstract base class for processing DidcvCallout
//-----------------------------------------------------------------------------
class DidcvCalloutApplicant
{
public:
virtual ~DidcvCalloutApplicant() { }
virtual BOOL Apply( DidcvCallout* pCallout ) = 0;
};
//-----------------------------------------------------------------------------
// Name: class DidcvCalloutSet
// Desc: a group of DidcvCallout references
// A callout is the line drawn from each axis/button to a label
//-----------------------------------------------------------------------------
class DidcvCalloutSet
{
public:
DidcvCalloutSet();
~DidcvCalloutSet();
public:
BOOL AddCallout( DidcvCallout* pCallout );
void Apply( DidcvCalloutApplicant* pCalloutApp );
void SetIdentifier( DWORD dwID );
DWORD GetIdentifier() const;
void SetData( void* pData );
void* GetData() const;
const GwArray <DidcvCallout*> & GetInternalArrayRef() const;
void TrimArrays();
protected:
void CleanUp();
protected:
GwArray <DidcvCallout*> m_calloutList;
DWORD m_dwSetID;
void* m_lpData;
};
//-----------------------------------------------------------------------------
// Name: class DidcvCalloutManager
// Desc: data structure for storing and managing callouts
// A callout is the line drawn from each axis/button to a label
//-----------------------------------------------------------------------------
class DidcvCalloutManager
{
public:
DidcvCalloutManager();
~DidcvCalloutManager();
// main interface
BOOL AddCallout( DidcvCallout* pCallout, INT nView );
BOOL SetCalloutState( const DidcvCalloutState* pCalloutState, DWORD dwObjID );
BOOL SetAllCalloutState( const DidcvCalloutState* pCalloutState );
BOOL SetActionMap( const LPDIACTION pAction, DWORD dwObjID );
void ClearAllActionMaps();
// information
DWORD GetObjectIDByLocation( const LPPOINT pPt, INT nView );
BOOL GetCalloutState( DidcvCalloutState* pCalloutState, DWORD dwObjID );
BOOL GetActionMap( DidcvActionMap* pActionMap, DWORD dwObjID );
const DidcvCalloutSet* GetCalloutSetByView( INT nView ) const;
const DidcvCalloutSet* GetCalloutSetByObjID( DWORD dwObjID ) const;
const DidcvCalloutData* GetCalloutDataRef( DWORD dwObjID ) const;
UINT GetNumUniqueCallouts() const;
BOOL EnumObjects( LPDIRECTINPUTDEVICE8 pDevice, LPDIENUMDEVICEOBJECTSCALLBACK pCallback, LPVOID pvRef, DWORD dwMapOnly );
BOOL CalcCanBeCollapsed();
// allocation
BOOL SetCapacity( DWORD dwNumCallouts, DWORD dwNumUniqueObjID, DWORD dwNumViews, BOOL bDeleteContent = TRUE );
void TrimArrays();
void CleanUp();
protected:
// helper functions
DidcvCalloutSet* Find( const GwArray <DidcvCalloutSet*> & array, DWORD dwIdentifier ) const;
DidcvCalloutData* GetCalloutData( DWORD dwObjID ) const;
protected:
// list of all callouts added
GwArray <DidcvCallout*> m_calloutList;
// list of callout sets, one for each unique callout id
GwArray <DidcvCalloutSet*> m_calloutSetListByObjID;
// list of callout sets, one for each view
GwArray <DidcvCalloutSet*> m_calloutSetListByView;
};
//-----------------------------------------------------------------------------
// Name: struct DidcvCalloutData
// Desc: data structure holding references to callout data components
//-----------------------------------------------------------------------------
struct DidcvCalloutData
{
DidcvCalloutState* lpState; // callout state info
DidcvActionMap* lpActionMap; // action mapped this callout
DidcvCalloutData( DidcvCalloutState* s, DidcvActionMap* a )
: lpState( s ), lpActionMap( a )
{ }
};
//-----------------------------------------------------------------------------
// Name: struct DidcvCalloutState
// Desc: state information for a callout
//-----------------------------------------------------------------------------
struct DidcvCalloutState
{
// whether to draw
BOOL bDrawCallout;
BOOL bDrawOverlay;
BOOL bDrawHighlight;
BOOL bDrawEmptyCallout;
BOOL bDrawFullname;
// specifies which state is valid
DWORD dwFlags;
// --- member functions ---
DidcvCalloutState( DWORD f = 0, BOOL c = FALSE, BOOL o = FALSE,
BOOL h = FALSE, BOOL e = FALSE, BOOL d = FALSE )
: dwFlags( f ), bDrawCallout( c ), bDrawOverlay( o ), bDrawHighlight( h ),
bDrawEmptyCallout( e ), bDrawFullname( d )
{ }
void SmartSet( const DidcvCalloutState* other );
void Copy( const DidcvCalloutState* other ) { *this = *other; }
DWORD MakeFlag() const;
void SetFlag( DWORD dwExtFlags );
};
//-----------------------------------------------------------------------------
// Name: struct DidcvActionMap
// Desc: action mapping information for a callout
//-----------------------------------------------------------------------------
struct DidcvActionMap
{
DIACTION dia;
DidcvActionMap() { ZeroMemory( &dia, sizeof( DIACTION ) ); }
void Copy( const DidcvActionMap* other ) { this->dia = other->dia; }
LPCSTR GetActionName() const { return dia.lptszActionName; }
};
// utility functions
void DidcvPolyLineArrow( HDC hDC, const POINT* rgpt, INT nPoints, BOOL bDoShadow = FALSE );
HFONT DidcvCreateFont( HDC hdc, const TCHAR* szFaceName, int iDeciPtHeight, int iDeciPtWidth, int iAttributes, BOOL fLogRes);
//-----------------------------------------------------------------------------
// Name: struct rgref
// Desc: templated lightweight c-style array
//-----------------------------------------------------------------------------
template <class T>
struct rgref {
rgref( T* p ) : pt( p ) {}
T & operator []( int i ) { return pt[i]; }
const T & operator []( int i ) const { return pt[i]; }
private:
T *pt;
};
//-----------------------------------------------------------------------------
// Name: struct SPOINT
// Desc: used by line drawing routine
//-----------------------------------------------------------------------------
struct SPOINT {
SPOINT()
#define SPOINT_INITIALIZERS \
p( u.p ), \
s( u.s ), \
a((( int* )( void* ) u.a ) ), \
x( u.p.x ), \
y( u.p.y ), \
cx( u.s.cx ), \
cy( u.s.cy )
: SPOINT_INITIALIZERS
{ x = y = 0; }
SPOINT( int, POINT *r )
: p( *r ),
s( *(( SIZE* )( void* ) r ) ),
a((( int* )( void* ) r ) ),
x( r->x ),
y( r->y ),
cx( r->x ),
cy( r->y )
{ }
SPOINT( const SPOINT & sp )
: SPOINT_INITIALIZERS
{ p = sp.p; }
SPOINT( int b, int c )
: SPOINT_INITIALIZERS
{ x = b; y = c; }
SPOINT( const POINT &point )
: SPOINT_INITIALIZERS
{ p = point; }
SPOINT( const SIZE &size )
: SPOINT_INITIALIZERS
{ s = size; }
#undef SPOINT_INITIALIZERS
SPOINT operator =( const SPOINT &sp ) { p = sp.p; return *this; }
SPOINT operator =( const POINT &_p ) { p = _p; return *this; }
SPOINT operator =( const SIZE &_s ) { s = _s; return *this; }
operator POINT() const { return p; }
operator SIZE() const { return s; }
long &x, &y, &cx, &cy;
POINT &p;
SIZE &s;
rgref<int> a;
private:
union {
POINT p;
SIZE s;
int a[2];
} u;
};
//-----------------------------------------------------------------------------
// Name: class DidcvBitmap
// Desc: object containing a bitmap
//-----------------------------------------------------------------------------
class DidcvBitmap
{
public:
~DidcvBitmap();
// drawing interface
BOOL Draw( HDC hDC, INT xStart, INT yStart);
BOOL Blend( HDC hDC, INT xStart, INT yStart );
BOOL Blend( VOID* lpBits, INT xStart, INT yStart, INT width, INT height );
// information
BOOL GetSize( SIZE* lpSize ) const;
HBITMAP GetHandle();
LPVOID GetBits();
public:
// static function for instantiating a DidcvBitmap
static DidcvBitmap* Create( LPCTSTR tszFilename );
static DidcvBitmap* Create( INT width, INT height );
private:
// private constructor
DidcvBitmap();
protected:
// helper functions
void CleanUp();
void FigureSize();
static DidcvBitmap* CreateViaD3dx( LPCTSTR tszFilename );
static DidcvBitmap* CreateViaLoadImage( HINSTANCE hinst, LPCTSTR tszName,
UINT uType, int cx, int cy, UINT fuLoad );
protected:
// GDI handle to bitmap
HBITMAP m_hbitmap;
VOID* m_lpBits;
SIZE m_size;
};
// alpha blending information
#define DIDCV_ALPHABLEND_DLL_NAME TEXT( "MSIMG32.DLL" )
#define DIDCV_ALPHABLEND_PROC_NAME TEXT( "AlphaBlend" )
#if( WINVER >= 0x400 )
typedef WINGDIAPI BOOL( WINAPI* DIDCV_ALPHABLEND )( HDC, int, int, int, int, HDC, int, int, int, int, BLENDFUNCTION );
#else
typedef DIDCV_ALPHABLEND DWORD
#endif
//-----------------------------------------------------------------------------
// Name: class DidcvAlphaBlend
// Desc: utility class for alpha blending
//-----------------------------------------------------------------------------
class DidcvAlphaBlend
{
public:
// reference counting interface
static BOOL AddClient();
static BOOL ReleaseClient();
// functions to perform blending
static BOOL Blend( HDC hDC, INT xStart, INT yStart, INT width, INT height, HBITMAP hbitmap, const SIZE* lpSize );
static BOOL Blend( VOID* lpDestBits, INT xStart, INT yStart, INT destWidth, INT destHeight, VOID* lpSrcBits, INT srcWidth, INT srcHeight );
protected:
static DIDCV_ALPHABLEND s_alphaBlendProc;
static HMODULE s_hDll;
static DWORD s_dwNumClients;
};
#endif // #ifndef __DIDCV_H__

View File

@@ -0,0 +1,62 @@
//-----------------------------------------------------------------------------
// File: DIUtil.h
//
// Desc: DirectInput support using action mapping
//
// Copyright (C) 1995-2001 Microsoft Corporation. All Rights Reserved.
//-----------------------------------------------------------------------------
#ifndef DIUTIL_H
#define DIUTIL_H
#include <dinput.h>
//-----------------------------------------------------------------------------
// Name: class CInputDeviceManager
// Desc: Input device manager using DX8 action mapping
//-----------------------------------------------------------------------------
class CInputDeviceManager
{
public:
struct DeviceInfo
{
LPDIRECTINPUTDEVICE8 pdidDevice;
LPVOID pParam;
};
typedef HRESULT (CALLBACK *LPDIMANAGERCALLBACK)(CInputDeviceManager::DeviceInfo* pDeviceInfo, const DIDEVICEINSTANCE* pdidi, LPVOID);
private:
BOOL m_bCleanupCOM;
HWND m_hWnd;
TCHAR* m_strUserName;
LPDIRECTINPUT8 m_pDI;
DeviceInfo* m_pDevices;
DWORD m_dwMaxDevices;
DWORD m_dwNumDevices;
DIACTIONFORMAT m_diaf;
LPDIMANAGERCALLBACK m_AddDeviceCallback;
LPVOID m_AddDeviceCallbackParam;
public:
// Device control
HRESULT AddDevice( const DIDEVICEINSTANCE* pdidi, LPDIRECTINPUTDEVICE8 pdidDevice );
HRESULT GetDevices( DeviceInfo** ppDeviceInfo, DWORD* pdwNumDevices );
HRESULT ConfigureDevices( HWND hWnd, IUnknown* pSurface, VOID* pCallback, DWORD dwFlags, LPVOID pvCBParam );
VOID UnacquireDevices();
VOID SetFocus( HWND hWnd );
// Construction
HRESULT SetActionFormat( DIACTIONFORMAT& diaf, BOOL bReenumerate );
HRESULT Create( HWND hWnd, TCHAR* strUserName, DIACTIONFORMAT& diaf, LPDIMANAGERCALLBACK AddDeviceCallback, LPVOID pCallbackParam );
CInputDeviceManager();
~CInputDeviceManager();
};
#endif

View File

@@ -0,0 +1,126 @@
//-----------------------------------------------------------------------------
// File: DMUtil.h
//
// Desc:
//
// Copyright (c) 1999-2001 Microsoft Corp. All rights reserved.
//-----------------------------------------------------------------------------
#ifndef DMUTIL_H
#define DMUTIL_H
#include <dmusicc.h>
#include <dmusici.h>
#include <dsound.h>
//-----------------------------------------------------------------------------
// Classes used by this header
//-----------------------------------------------------------------------------
class CMusicManager;
class CMusicSegment;
class CMusicScript;
//-----------------------------------------------------------------------------
// Name: class CMusicManager
// Desc:
//-----------------------------------------------------------------------------
class CMusicManager
{
protected:
BOOL m_bCleanupCOM;
IDirectMusicLoader8* m_pLoader;
IDirectMusicPerformance8* m_pPerformance;
public:
CMusicManager();
~CMusicManager();
inline IDirectMusicLoader8* GetLoader() { return m_pLoader; }
inline IDirectMusicPerformance8* GetPerformance() { return m_pPerformance; }
IDirectMusicAudioPath8* GetDefaultAudioPath();
HRESULT Initialize( HWND hWnd, DWORD dwPChannels = 128, DWORD dwDefaultPathType = DMUS_APATH_DYNAMIC_STEREO );
HRESULT SetSearchDirectory( const TCHAR* strMediaPath );
VOID CollectGarbage();
HRESULT CreateSegmentFromFile( CMusicSegment** ppSegment, TCHAR* strFileName,
BOOL bDownloadNow = TRUE, BOOL bIsMidiFile = FALSE );
HRESULT CreateScriptFromFile( CMusicScript** ppScript, TCHAR* strFileName );
HRESULT CreateChordMapFromFile( IDirectMusicChordMap8** ppChordMap, TCHAR* strFileName );
HRESULT CreateStyleFromFile( IDirectMusicStyle8** ppStyle, TCHAR* strFileName );
HRESULT GetMotifFromStyle( IDirectMusicSegment8** ppMotif, TCHAR* strStyle, TCHAR* wstrMotif );
HRESULT CreateSegmentFromResource( CMusicSegment** ppSegment, TCHAR* strResource, TCHAR* strResourceType,
BOOL bDownloadNow = TRUE, BOOL bIsMidiFile = FALSE );
};
//-----------------------------------------------------------------------------
// Name: class CMusicSegment
// Desc: Encapsulates functionality of an IDirectMusicSegment
//-----------------------------------------------------------------------------
class CMusicSegment
{
protected:
IDirectMusicSegment8* m_pSegment;
IDirectMusicLoader8* m_pLoader;
IDirectMusicPerformance8* m_pPerformance;
IDirectMusicAudioPath8* m_pEmbeddedAudioPath;
BOOL m_bDownloaded;
public:
CMusicSegment( IDirectMusicPerformance8* pPerformance,
IDirectMusicLoader8* pLoader,
IDirectMusicSegment8* pSegment );
virtual ~CMusicSegment();
inline IDirectMusicSegment8* GetSegment() { return m_pSegment; }
HRESULT GetStyle( IDirectMusicStyle8** ppStyle, DWORD dwStyleIndex = 0 );
HRESULT SetRepeats( DWORD dwRepeats );
HRESULT Play( DWORD dwFlags = DMUS_SEGF_SECONDARY, IDirectMusicAudioPath8* pAudioPath = NULL );
HRESULT Stop( DWORD dwFlags = 0 );
HRESULT Download( IDirectMusicAudioPath8* pAudioPath = NULL );
HRESULT Unload( IDirectMusicAudioPath8* pAudioPath = NULL );
BOOL IsPlaying();
};
//-----------------------------------------------------------------------------
// Name: class CMusicScript
// Desc: Encapsulates functionality of an IDirectMusicScript
//-----------------------------------------------------------------------------
class CMusicScript
{
protected:
IDirectMusicScript8* m_pScript;
IDirectMusicLoader8* m_pLoader;
IDirectMusicPerformance8* m_pPerformance;
public:
CMusicScript( IDirectMusicPerformance8* pPerformance,
IDirectMusicLoader8* pLoader,
IDirectMusicScript8* pScript );
virtual ~CMusicScript();
inline IDirectMusicScript8* GetScript() { return m_pScript; }
HRESULT CallRoutine( TCHAR* strRoutine );
HRESULT SetVariableNumber( TCHAR* strVariable, LONG lValue );
HRESULT GetVariableNumber( TCHAR* strVariable, LONG* plValue );
};
#endif // DMUTIL_H

View File

@@ -0,0 +1,171 @@
//-----------------------------------------------------------------------------
// File: DSUtil.h
//
// Desc:
//
// Copyright (c) 1999-2001 Microsoft Corp. All rights reserved.
//-----------------------------------------------------------------------------
#ifndef DSUTIL_H
#define DSUTIL_H
#include <windows.h>
#include <mmsystem.h>
#include <mmreg.h>
#include <dsound.h>
//-----------------------------------------------------------------------------
// Classes used by this header
//-----------------------------------------------------------------------------
class CSoundManager;
class CSound;
class CStreamingSound;
class CWaveFile;
//-----------------------------------------------------------------------------
// Typing macros
//-----------------------------------------------------------------------------
#define WAVEFILE_READ 1
#define WAVEFILE_WRITE 2
#define DSUtil_StopSound(s) { if(s) s->Stop(); }
#define DSUtil_PlaySound(s) { if(s) s->Play( 0, 0 ); }
#define DSUtil_PlaySoundLooping(s) { if(s) s->Play( 0, DSBPLAY_LOOPING ); }
//-----------------------------------------------------------------------------
// Name: class CSoundManager
// Desc:
//-----------------------------------------------------------------------------
class CSoundManager
{
protected:
LPDIRECTSOUND8 m_pDS;
public:
CSoundManager();
~CSoundManager();
HRESULT Initialize( HWND hWnd, DWORD dwCoopLevel, DWORD dwPrimaryChannels, DWORD dwPrimaryFreq, DWORD dwPrimaryBitRate );
inline LPDIRECTSOUND8 GetDirectSound() { return m_pDS; }
HRESULT SetPrimaryBufferFormat( DWORD dwPrimaryChannels, DWORD dwPrimaryFreq, DWORD dwPrimaryBitRate );
HRESULT Get3DListenerInterface( LPDIRECTSOUND3DLISTENER* ppDSListener );
HRESULT Create( CSound** ppSound, LPTSTR strWaveFileName, DWORD dwCreationFlags = 0, GUID guid3DAlgorithm = GUID_NULL, DWORD dwNumBuffers = 1 );
HRESULT CreateFromMemory( CSound** ppSound, BYTE* pbData, ULONG ulDataSize, LPWAVEFORMATEX pwfx, DWORD dwCreationFlags = 0, GUID guid3DAlgorithm = GUID_NULL, DWORD dwNumBuffers = 1 );
HRESULT CreateStreaming( CStreamingSound** ppStreamingSound, LPTSTR strWaveFileName, DWORD dwCreationFlags, GUID guid3DAlgorithm, DWORD dwNotifyCount, DWORD dwNotifySize, HANDLE hNotifyEvent );
};
//-----------------------------------------------------------------------------
// Name: class CSound
// Desc: Encapsulates functionality of a DirectSound buffer.
//-----------------------------------------------------------------------------
class CSound
{
protected:
LPDIRECTSOUNDBUFFER* m_apDSBuffer;
DWORD m_dwDSBufferSize;
CWaveFile* m_pWaveFile;
DWORD m_dwNumBuffers;
HRESULT RestoreBuffer( LPDIRECTSOUNDBUFFER pDSB, BOOL* pbWasRestored );
public:
CSound( LPDIRECTSOUNDBUFFER* apDSBuffer, DWORD dwDSBufferSize, DWORD dwNumBuffers, CWaveFile* pWaveFile );
virtual ~CSound();
HRESULT Get3DBufferInterface( DWORD dwIndex, LPDIRECTSOUND3DBUFFER* ppDS3DBuffer );
HRESULT FillBufferWithSound( LPDIRECTSOUNDBUFFER pDSB, BOOL bRepeatWavIfBufferLarger );
LPDIRECTSOUNDBUFFER GetFreeBuffer();
LPDIRECTSOUNDBUFFER GetBuffer( DWORD dwIndex );
HRESULT Play( DWORD dwPriority = 0, DWORD dwFlags = 0 );
HRESULT Stop();
HRESULT Reset();
BOOL IsSoundPlaying();
};
//-----------------------------------------------------------------------------
// Name: class CStreamingSound
// Desc: Encapsulates functionality to play a wave file with DirectSound.
// The Create() method loads a chunk of wave file into the buffer,
// and as sound plays more is written to the buffer by calling
// HandleWaveStreamNotification() whenever hNotifyEvent is signaled.
//-----------------------------------------------------------------------------
class CStreamingSound : public CSound
{
protected:
DWORD m_dwLastPlayPos;
DWORD m_dwPlayProgress;
DWORD m_dwNotifySize;
DWORD m_dwNextWriteOffset;
BOOL m_bFillNextNotificationWithSilence;
public:
CStreamingSound( LPDIRECTSOUNDBUFFER pDSBuffer, DWORD dwDSBufferSize, CWaveFile* pWaveFile, DWORD dwNotifySize );
~CStreamingSound();
HRESULT HandleWaveStreamNotification( BOOL bLoopedPlay );
HRESULT Reset();
};
//-----------------------------------------------------------------------------
// Name: class CWaveFile
// Desc: Encapsulates reading or writing sound data to or from a wave file
//-----------------------------------------------------------------------------
class CWaveFile
{
public:
WAVEFORMATEX* m_pwfx; // Pointer to WAVEFORMATEX structure
HMMIO m_hmmio; // MM I/O handle for the WAVE
MMCKINFO m_ck; // Multimedia RIFF chunk
MMCKINFO m_ckRiff; // Use in opening a WAVE file
DWORD m_dwSize; // The size of the wave file
MMIOINFO m_mmioinfoOut;
DWORD m_dwFlags;
BOOL m_bIsReadingFromMemory;
BYTE* m_pbData;
BYTE* m_pbDataCur;
ULONG m_ulDataSize;
CHAR* m_pResourceBuffer;
protected:
HRESULT ReadMMIO();
HRESULT WriteMMIO( WAVEFORMATEX *pwfxDest );
public:
CWaveFile();
~CWaveFile();
HRESULT Open( LPTSTR strFileName, WAVEFORMATEX* pwfx, DWORD dwFlags );
HRESULT OpenFromMemory( BYTE* pbData, ULONG ulDataSize, WAVEFORMATEX* pwfx, DWORD dwFlags );
HRESULT Close();
HRESULT Read( BYTE* pBuffer, DWORD dwSizeToRead, DWORD* pdwSizeRead );
HRESULT Write( UINT nSizeToWrite, BYTE* pbData, UINT* pnSizeWrote );
DWORD GetSize();
HRESULT ResetFile();
WAVEFORMATEX* GetFormat() { return m_pwfx; };
};
#endif // DSUTIL_H

View File

@@ -0,0 +1,112 @@
//-----------------------------------------------------------------------------
// File: DXUtil.h
//
// Desc: Helper functions and typing shortcuts for DirectX programming.
//
// Copyright (c) 1997-2001 Microsoft Corporation. All rights reserved
//-----------------------------------------------------------------------------
#ifndef DXUTIL_H
#define DXUTIL_H
//-----------------------------------------------------------------------------
// Miscellaneous helper functions
//-----------------------------------------------------------------------------
#define SAFE_DELETE(p) { if(p) { delete (p); (p)=NULL; } }
#define SAFE_DELETE_ARRAY(p) { if(p) { delete[] (p); (p)=NULL; } }
#define SAFE_RELEASE(p) { if(p) { (p)->Release(); (p)=NULL; } }
//-----------------------------------------------------------------------------
// Name: DXUtil_GetDXSDKMediaPath() and DXUtil_FindMediaFile()
// Desc: Returns the DirectX SDK path, as stored in the system registry
// during the SDK install.
//-----------------------------------------------------------------------------
const TCHAR* DXUtil_GetDXSDKMediaPath();
HRESULT DXUtil_FindMediaFile( TCHAR* strPath, TCHAR* strFilename );
//-----------------------------------------------------------------------------
// Name: DXUtil_Read*RegKey() and DXUtil_Write*RegKey()
// Desc: Helper functions to read/write a string registry key
//-----------------------------------------------------------------------------
HRESULT DXUtil_WriteStringRegKey( HKEY hKey, TCHAR* strRegName, TCHAR* strValue );
HRESULT DXUtil_WriteIntRegKey( HKEY hKey, TCHAR* strRegName, DWORD dwValue );
HRESULT DXUtil_WriteGuidRegKey( HKEY hKey, TCHAR* strRegName, GUID guidValue );
HRESULT DXUtil_WriteBoolRegKey( HKEY hKey, TCHAR* strRegName, BOOL bValue );
HRESULT DXUtil_ReadStringRegKey( HKEY hKey, TCHAR* strRegName, TCHAR* strValue, DWORD dwLength, TCHAR* strDefault );
HRESULT DXUtil_ReadIntRegKey( HKEY hKey, TCHAR* strRegName, DWORD* pdwValue, DWORD dwDefault );
HRESULT DXUtil_ReadGuidRegKey( HKEY hKey, TCHAR* strRegName, GUID* pGuidValue, GUID& guidDefault );
HRESULT DXUtil_ReadBoolRegKey( HKEY hKey, TCHAR* strRegName, BOOL* pbValue, BOOL bDefault );
//-----------------------------------------------------------------------------
// Name: DXUtil_Timer()
// Desc: Performs timer opertations. Use the following commands:
// TIMER_RESET - to reset the timer
// TIMER_START - to start the timer
// TIMER_STOP - to stop (or pause) the timer
// TIMER_ADVANCE - to advance the timer by 0.1 seconds
// TIMER_GETABSOLUTETIME - to get the absolute system time
// TIMER_GETAPPTIME - to get the current time
// TIMER_GETELAPSEDTIME - to get the time that elapsed between
// TIMER_GETELAPSEDTIME calls
//-----------------------------------------------------------------------------
enum TIMER_COMMAND { TIMER_RESET, TIMER_START, TIMER_STOP, TIMER_ADVANCE,
TIMER_GETABSOLUTETIME, TIMER_GETAPPTIME, TIMER_GETELAPSEDTIME };
FLOAT __stdcall DXUtil_Timer( TIMER_COMMAND command );
//-----------------------------------------------------------------------------
// UNICODE support for converting between CHAR, TCHAR, and WCHAR strings
//-----------------------------------------------------------------------------
VOID DXUtil_ConvertAnsiStringToWide( WCHAR* wstrDestination, const CHAR* strSource, int cchDestChar = -1 );
VOID DXUtil_ConvertWideStringToAnsi( CHAR* strDestination, const WCHAR* wstrSource, int cchDestChar = -1 );
VOID DXUtil_ConvertGenericStringToAnsi( CHAR* strDestination, const TCHAR* tstrSource, int cchDestChar = -1 );
VOID DXUtil_ConvertGenericStringToWide( WCHAR* wstrDestination, const TCHAR* tstrSource, int cchDestChar = -1 );
VOID DXUtil_ConvertAnsiStringToGeneric( TCHAR* tstrDestination, const CHAR* strSource, int cchDestChar = -1 );
VOID DXUtil_ConvertWideStringToGeneric( TCHAR* tstrDestination, const WCHAR* wstrSource, int cchDestChar = -1 );
//-----------------------------------------------------------------------------
// GUID to String converting
//-----------------------------------------------------------------------------
VOID DXUtil_ConvertGUIDToString( const GUID* pGuidIn, TCHAR* strOut );
BOOL DXUtil_ConvertStringToGUID( const TCHAR* strIn, GUID* pGuidOut );
//-----------------------------------------------------------------------------
// Debug printing support
//-----------------------------------------------------------------------------
VOID DXUtil_Trace( TCHAR* strMsg, ... );
HRESULT _DbgOut( TCHAR*, DWORD, HRESULT, TCHAR* );
#if defined(DEBUG) | defined(_DEBUG)
#define DXTRACE DXUtil_Trace
#else
#define DXTRACE sizeof
#endif
#if defined(DEBUG) | defined(_DEBUG)
#define DEBUG_MSG(str) _DbgOut( __FILE__, (DWORD)__LINE__, 0, str )
#else
#define DEBUG_MSG(str) (0L)
#endif
#endif // DXUTIL_H

View File

@@ -0,0 +1,102 @@
//-----------------------------------------------------------------------------
// File: NetConnect.h
//
// Desc:
//
// Copyright (C) 2000-2001 Microsoft Corporation. All Rights Reserved.
//-----------------------------------------------------------------------------
#ifndef NETCLIENT_H
#define NETCLIENT_H
#include <windows.h>
#include <dplay8.h>
#include <dpaddr.h>
#include <tchar.h>
//-----------------------------------------------------------------------------
// Defines, structures, and error codes
//-----------------------------------------------------------------------------
#define DISPLAY_REFRESH_RATE 250
#define TIMERID_DISPLAY_HOSTS 1
#define TIMERID_CONNECT_COMPLETE 2
#define NCW_S_FORWARD 0x01000001 // Dialog success, so go forward
#define NCW_S_BACKUP 0x01000002 // Dialog canceled, show previous dialog
#define NCW_S_QUIT 0x01000003 // Dialog quit, close app
#define NCW_S_LOBBYCONNECT 0x01000004 // Dialog connected from lobby, connect success
class CNetClientWizard
{
public:
CNetClientWizard( HINSTANCE hInst, TCHAR* strAppName, GUID* pGuidApp );
virtual ~CNetClientWizard();
HRESULT WINAPI MessageHandler( PVOID pvUserContext, DWORD dwMessageId, PVOID pMsgBuffer );
HRESULT WINAPI LobbyMessageHandler( PVOID pvUserContext, DWORD dwMessageId, PVOID pMsgBuffer );
VOID Init( IDirectPlay8Client* pDPClient, IDirectPlay8LobbiedApplication* pLobbiedApp );
HRESULT DoConnectWizard();
HRESULT ConnectUsingLobbySettings();
void SetPlayerName( TCHAR* strPlayerName ) { _tcscpy( m_strLocalPlayerName, strPlayerName ); }
TCHAR* GetPlayerName() { return m_strLocalPlayerName; }
BOOL HaveConnectionSettingsFromLobby() { return m_bHaveConnectionSettingsFromLobby; }
protected:
struct DPHostEnumInfo
{
DWORD dwRef;
DPN_APPLICATION_DESC* pAppDesc;
IDirectPlay8Address* pHostAddr;
IDirectPlay8Address* pDeviceAddr;
TCHAR szSession[MAX_PATH];
DWORD dwLastPollTime;
BOOL bValid;
DPHostEnumInfo* pNext;
};
static INT_PTR CALLBACK StaticSessionsDlgProc( HWND, UINT, WPARAM, LPARAM );
static INT_PTR CALLBACK StaticLobbyWaitDlgProc( HWND, UINT, WPARAM, LPARAM );
INT_PTR CALLBACK SessionsDlgProc( HWND, UINT, WPARAM, LPARAM );
INT_PTR CALLBACK LobbyWaitDlgProc( HWND, UINT, WPARAM, LPARAM );
VOID SessionsDlgInitListbox( HWND hDlg );
HRESULT SessionsDlgEnumHosts( HWND hDlg );
HRESULT SessionsDlgNoteEnumResponse( PDPNMSG_ENUM_HOSTS_RESPONSE pEnumHostsResponse );
VOID SessionsDlgExpireOldHostEnums();
HRESULT SessionsDlgDisplayEnumList( HWND hDlg );
HRESULT SessionsDlgJoinGame( HWND hDlg );
HRESULT SessionsDlgCreateGame( HWND hDlg );
VOID SessionsDlgEnumListCleanup();
IDirectPlay8Client* m_pDPClient;
IDirectPlay8LobbiedApplication* m_pLobbiedApp;
CRITICAL_SECTION m_csHostEnum;
GUID m_guidApp;
HRESULT m_hrDialog;
HWND m_hDlg;
HINSTANCE m_hInst;
DPHostEnumInfo m_DPHostEnumHead;
TCHAR m_strAppName[MAX_PATH];
TCHAR m_strLocalPlayerName[MAX_PATH];
BOOL m_bSearchingForSessions;
BOOL m_bEnumListChanged;
DPNHANDLE m_hEnumAsyncOp;
DWORD m_dwEnumHostExpireInterval;
BOOL m_bConnecting;
DPNHANDLE m_hConnectAsyncOp;
HANDLE m_hConnectCompleteEvent;
HANDLE m_hLobbyConnectionEvent;
HRESULT m_hrConnectComplete;
BOOL m_bHaveConnectionSettingsFromLobby;
DPNHANDLE m_hLobbyClient;
};
#endif // NETCLIENT_H

View File

@@ -0,0 +1,8 @@
#define IDD_CLIENT_CONNECT 12001
#define IDC_PLAYER_NAME_EDIT 12100
#define IDC_GAMES_LIST 12101
#define IDC_JOIN 12102
#define IDC_IP_ADDRESS 12103
#define IDC_SEARCH_CHECK 12104
#define IDC_WAIT_TEXT 12105
#define IDI_MAIN 12200

View File

@@ -0,0 +1,125 @@
//-----------------------------------------------------------------------------
// File: NetConnect.h
//
// Desc:
//
// Copyright (C) 2000-2001 Microsoft Corporation. All Rights Reserved.
//-----------------------------------------------------------------------------
#ifndef NETCONNECT_H
#define NETCONNECT_H
#include <windows.h>
#include <dplay8.h>
#include <dpaddr.h>
#include <tchar.h>
//-----------------------------------------------------------------------------
// Defines, structures, and error codes
//-----------------------------------------------------------------------------
#define DISPLAY_REFRESH_RATE 250
#define TIMERID_DISPLAY_HOSTS 1
#define TIMERID_CONNECT_COMPLETE 2
#define NCW_S_FORWARD 0x01000001 // Dialog success, so go forward
#define NCW_S_BACKUP 0x01000002 // Dialog canceled, show previous dialog
#define NCW_S_QUIT 0x01000003 // Dialog quit, close app
#define NCW_S_LOBBYCONNECT 0x01000004 // Dialog connected from lobby, connect success
class CNetConnectWizard
{
public:
CNetConnectWizard( HINSTANCE hInst, HWND hWndParent, TCHAR* strAppName, GUID* pGuidApp );
virtual ~CNetConnectWizard();
HRESULT WINAPI MessageHandler( PVOID pvUserContext, DWORD dwMessageId, PVOID pMsgBuffer );
HRESULT WINAPI LobbyMessageHandler( PVOID pvUserContext, DWORD dwMessageId, PVOID pMsgBuffer );
VOID Init( IDirectPlay8Peer* pDP, IDirectPlay8LobbiedApplication* pLobbiedApp );
VOID Shutdown();
HRESULT DoConnectWizard( BOOL bBackTrack );
HRESULT ConnectUsingLobbySettings();
void SetMaxPlayers( DWORD dwMaxPlayers ) { m_dwMaxPlayers = dwMaxPlayers; }
void SetPlayerName( TCHAR* strPlayerName ) { _tcscpy( m_strLocalPlayerName, strPlayerName ); }
void SetSessionName( TCHAR* strSessionName ) { _tcscpy( m_strSessionName, strSessionName ); }
void SetPreferredProvider( TCHAR* strPreferredProvider ) { _tcscpy( m_strPreferredProvider, strPreferredProvider ); }
TCHAR* GetPlayerName() { return m_strLocalPlayerName; }
TCHAR* GetSessionName() { return m_strSessionName; }
TCHAR* GetPreferredProvider() { return m_strPreferredProvider; }
BOOL IsHostPlayer() { return m_bHostPlayer; }
BOOL IsMigrateHost() { return m_bMigrateHost; }
BOOL HaveConnectionSettingsFromLobby() { return m_bHaveConnectionSettingsFromLobby; }
protected:
struct DPHostEnumInfo
{
DWORD dwRef;
DPN_APPLICATION_DESC* pAppDesc;
IDirectPlay8Address* pHostAddr;
IDirectPlay8Address* pDeviceAddr;
TCHAR szSession[MAX_PATH];
DWORD dwLastPollTime;
BOOL bValid;
DPHostEnumInfo* pNext;
};
static INT_PTR CALLBACK StaticConnectionsDlgProc( HWND, UINT, WPARAM, LPARAM );
static INT_PTR CALLBACK StaticSessionsDlgProc( HWND, UINT, WPARAM, LPARAM );
static INT_PTR CALLBACK StaticCreateSessionDlgProc( HWND, UINT, WPARAM, LPARAM );
static INT_PTR CALLBACK StaticLobbyWaitDlgProc( HWND, UINT, WPARAM, LPARAM );
INT_PTR CALLBACK ConnectionsDlgProc( HWND, UINT, WPARAM, LPARAM );
INT_PTR CALLBACK SessionsDlgProc( HWND, UINT, WPARAM, LPARAM );
INT_PTR CALLBACK CreateSessionDlgProc( HWND, UINT, WPARAM, LPARAM );
INT_PTR CALLBACK LobbyWaitDlgProc( HWND, UINT, WPARAM, LPARAM );
HRESULT ConnectionsDlgFillListBox( HWND hDlg );
HRESULT ConnectionsDlgOnOK( HWND hDlg );
VOID ConnectionsDlgCleanup( HWND hDlg );
VOID SessionsDlgInitListbox( HWND hDlg );
HRESULT SessionsDlgEnumHosts( HWND hDlg );
HRESULT SessionsDlgNoteEnumResponse( PDPNMSG_ENUM_HOSTS_RESPONSE pEnumHostsResponse );
VOID SessionsDlgExpireOldHostEnums();
HRESULT SessionsDlgDisplayEnumList( HWND hDlg );
HRESULT SessionsDlgJoinGame( HWND hDlg );
HRESULT SessionsDlgCreateGame( HWND hDlg );
VOID SessionsDlgEnumListCleanup();
IDirectPlay8Peer* m_pDP;
IDirectPlay8LobbiedApplication* m_pLobbiedApp;
CRITICAL_SECTION m_csHostEnum;
GUID m_guidApp;
HRESULT m_hrDialog;
HWND m_hDlg;
HINSTANCE m_hInst;
HWND m_hWndParent;
DWORD m_dwMaxPlayers;
TCHAR m_strAppName[MAX_PATH];
TCHAR m_strPreferredProvider[MAX_PATH];
TCHAR m_strSessionName[MAX_PATH];
TCHAR m_strLocalPlayerName[MAX_PATH];
BOOL m_bSearchingForSessions;
BOOL m_bMigrateHost;
IDirectPlay8Address* m_pDeviceAddress;
IDirectPlay8Address* m_pHostAddress;
DPHostEnumInfo m_DPHostEnumHead;
BOOL m_bEnumListChanged;
DPNHANDLE m_hEnumAsyncOp;
BOOL m_bHostPlayer;
DWORD m_dwEnumHostExpireInterval;
BOOL m_bConnecting;
DPNHANDLE m_hConnectAsyncOp;
HANDLE m_hConnectCompleteEvent;
HANDLE m_hLobbyConnectionEvent;
HRESULT m_hrConnectComplete;
BOOL m_bHaveConnectionSettingsFromLobby;
DPNHANDLE m_hLobbyClient;
};
#endif // NETCONNECT_H

View File

@@ -0,0 +1,18 @@
#define IDD_MULTIPLAYER_CONNECT 10001
#define IDD_MULTIPLAYER_GAMES 10002
#define IDD_MULTIPLAYER_CREATE 10003
#define IDD_LOBBY_WAIT_STATUS 10004
#define IDC_RETURN 11001
#define IDC_PLAYER_NAME_EDIT 11002
#define IDC_GAMES_LIST 11003
#define IDC_JOIN 11004
#define IDC_CREATE 11005
#define IDC_CONNECTION_LIST 11006
#define IDC_BACK 11007
#define IDC_EDIT_SESSION_NAME 11009
#define IDC_SEARCH_CHECK 11010
#define IDC_LOBBYCONNECTCANCEL 11011
#define IDC_WAIT_TEXT 11012
#define IDC_MIGRATE_HOST 11013
#define IDI_MAIN 11014

View File

@@ -0,0 +1,53 @@
//-----------------------------------------------------------------------------
// File: NetVoice.h
//
// Desc:
//
// Copyright (C) 2000-2001 Microsoft Corporation. All Rights Reserved.
//-----------------------------------------------------------------------------
#ifndef NETVOICE_H
#define NETVOICE_H
#include <windows.h>
#include <dvoice.h>
class CNetVoice
{
public:
CNetVoice( LPDVMESSAGEHANDLER pfnDirectPlayClientVoiceMessageHandler,
LPDVMESSAGEHANDLER pfnDirectPlayServerVoiceMessageHandler );
virtual ~CNetVoice();
HRESULT Init( HWND hDlg, BOOL bCreateSession, BOOL bConnectToSession,
LPUNKNOWN pDirectPlay, DWORD dwSessionType, GUID* pGuidCT,
DVCLIENTCONFIG* pdvClientConfig, LPDIRECTSOUND lpds = NULL );
HRESULT Free();
HRESULT HostMigrate( LPDIRECTPLAYVOICESERVER pdvServerInterface );
HRESULT IsHalfDuplex() { return m_bHalfDuplex; }
HRESULT ChangeVoiceClientSettings( DVCLIENTCONFIG* pdvClientConfig );
LPDIRECTPLAYVOICECLIENT GetVoiceClient() { return m_pVoiceClient; }
LPDIRECTPLAYVOICESERVER GetVoiceServer() { return m_pVoiceServer; }
protected:
LPDIRECTPLAYVOICECLIENT m_pVoiceClient;
LPDIRECTPLAYVOICESERVER m_pVoiceServer;
LPDVMESSAGEHANDLER m_pfnDirectPlayClientVoiceMessageHandler;
LPDVMESSAGEHANDLER m_pfnDirectPlayServerVoiceMessageHandler;
HRESULT VoiceSessionCreate( LPUNKNOWN pDirectPlay, DWORD dwSessionType, GUID* pGuidCT );
HRESULT VoiceSessionTestAudioSetup( HWND hDlg );
HRESULT VoiceSessionConnect( HWND hDlg, LPUNKNOWN pDirectPlay,
DVCLIENTCONFIG* pdvClientConfig, LPDIRECTSOUND lpds = NULL );
HRESULT VoiceSessionDisconnect();
HRESULT VoiceSessionDestroy();
HRESULT m_bHalfDuplex;
};
#endif // NETVOICE_H

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,808 @@
//-----------------------------------------------------------------------------
// File: D3DFile.cpp
//
// Desc: Support code for loading DirectX .X files.
//
// Copyright (c) 1997-2001 Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#define STRICT
#include <tchar.h>
#include <stdio.h>
#include <d3d8.h>
#include <d3dx8.h>
#include <dxfile.h>
#include <rmxfguid.h>
#include <rmxftmpl.h>
#include "D3DFile.h"
#include "DXUtil.h"
//-----------------------------------------------------------------------------
// Name:
// Desc:
//-----------------------------------------------------------------------------
CD3DMesh::CD3DMesh( TCHAR* strName )
{
_tcscpy( m_strName, strName );
m_pSysMemMesh = NULL;
m_pLocalMesh = NULL;
m_dwNumMaterials = 0L;
m_pMaterials = NULL;
m_pTextures = NULL;
m_bUseMaterials = TRUE;
}
//-----------------------------------------------------------------------------
// Name:
// Desc:
//-----------------------------------------------------------------------------
CD3DMesh::~CD3DMesh()
{
Destroy();
}
//-----------------------------------------------------------------------------
// Name:
// Desc:
//-----------------------------------------------------------------------------
HRESULT CD3DMesh::Create( LPDIRECT3DDEVICE8 pd3dDevice, TCHAR* strFilename )
{
TCHAR strPath[MAX_PATH];
CHAR strPathANSI[MAX_PATH];
LPD3DXBUFFER pAdjacencyBuffer = NULL;
LPD3DXBUFFER pMtrlBuffer = NULL;
HRESULT hr;
// Find the path for the file, and convert it to ANSI (for the D3DX API)
DXUtil_FindMediaFile( strPath, strFilename );
DXUtil_ConvertGenericStringToAnsi( strPathANSI, strPath );
// Load the mesh
if( FAILED( hr = D3DXLoadMeshFromX( strPathANSI, D3DXMESH_SYSTEMMEM, pd3dDevice,
&pAdjacencyBuffer, &pMtrlBuffer,
&m_dwNumMaterials, &m_pSysMemMesh ) ) )
{
return hr;
}
// Optimize the mesh for performance
if( FAILED( hr = m_pSysMemMesh->OptimizeInplace(
D3DXMESHOPT_COMPACT | D3DXMESHOPT_ATTRSORT | D3DXMESHOPT_VERTEXCACHE,
(DWORD*)pAdjacencyBuffer->GetBufferPointer(), NULL, NULL, NULL ) ) )
{
SAFE_RELEASE( pAdjacencyBuffer );
SAFE_RELEASE( pMtrlBuffer );
return hr;
}
// Get material info for the mesh
// Get the array of materials out of the buffer
if( pMtrlBuffer && m_dwNumMaterials > 0 )
{
// Allocate memory for the materials and textures
D3DXMATERIAL* d3dxMtrls = (D3DXMATERIAL*)pMtrlBuffer->GetBufferPointer();
m_pMaterials = new D3DMATERIAL8[m_dwNumMaterials];
m_pTextures = new LPDIRECT3DTEXTURE8[m_dwNumMaterials];
// Copy each material and create its texture
for( DWORD i=0; i<m_dwNumMaterials; i++ )
{
// Copy the material
m_pMaterials[i] = d3dxMtrls[i].MatD3D;
m_pMaterials[i].Ambient = m_pMaterials[i].Diffuse;
m_pTextures[i] = NULL;
// Create a texture
if( d3dxMtrls[i].pTextureFilename )
{
TCHAR strTexture[MAX_PATH];
TCHAR strTextureTemp[MAX_PATH];
DXUtil_ConvertAnsiStringToGeneric( strTextureTemp, d3dxMtrls[i].pTextureFilename );
DXUtil_FindMediaFile( strTexture, strTextureTemp );
if( FAILED( D3DXCreateTextureFromFile( pd3dDevice, strTexture,
&m_pTextures[i] ) ) )
m_pTextures[i] = NULL;
}
}
}
SAFE_RELEASE( pAdjacencyBuffer );
SAFE_RELEASE( pMtrlBuffer );
return S_OK;
}
//-----------------------------------------------------------------------------
// Name:
// Desc:
//-----------------------------------------------------------------------------
HRESULT CD3DMesh::Create( LPDIRECT3DDEVICE8 pd3dDevice,
LPDIRECTXFILEDATA pFileData )
{
LPD3DXBUFFER pMtrlBuffer = NULL;
LPD3DXBUFFER pAdjacencyBuffer = NULL;
HRESULT hr;
// Load the mesh from the DXFILEDATA object
if( FAILED( hr = D3DXLoadMeshFromXof( pFileData, D3DXMESH_SYSTEMMEM, pd3dDevice,
&pAdjacencyBuffer, &pMtrlBuffer,
&m_dwNumMaterials, &m_pSysMemMesh ) ) )
{
return hr;
}
// Optimize the mesh for performance
if( FAILED( hr = m_pSysMemMesh->OptimizeInplace(
D3DXMESHOPT_COMPACT | D3DXMESHOPT_ATTRSORT | D3DXMESHOPT_VERTEXCACHE,
(DWORD*)pAdjacencyBuffer->GetBufferPointer(), NULL, NULL, NULL ) ) )
{
SAFE_RELEASE( pAdjacencyBuffer );
SAFE_RELEASE( pMtrlBuffer );
return hr;
}
// Get material info for the mesh
// Get the array of materials out of the buffer
if( pMtrlBuffer && m_dwNumMaterials > 0 )
{
// Allocate memory for the materials and textures
D3DXMATERIAL* d3dxMtrls = (D3DXMATERIAL*)pMtrlBuffer->GetBufferPointer();
m_pMaterials = new D3DMATERIAL8[m_dwNumMaterials];
m_pTextures = new LPDIRECT3DTEXTURE8[m_dwNumMaterials];
// Copy each material and create its texture
for( DWORD i=0; i<m_dwNumMaterials; i++ )
{
// Copy the material
m_pMaterials[i] = d3dxMtrls[i].MatD3D;
m_pMaterials[i].Ambient = m_pMaterials[i].Diffuse;
m_pTextures[i] = NULL;
// Create a texture
if( d3dxMtrls[i].pTextureFilename )
{
TCHAR strTexture[MAX_PATH];
TCHAR strTextureTemp[MAX_PATH];
DXUtil_ConvertAnsiStringToGeneric( strTextureTemp, d3dxMtrls[i].pTextureFilename );
DXUtil_FindMediaFile( strTexture, strTextureTemp );
if( FAILED( D3DXCreateTextureFromFile( pd3dDevice, strTexture,
&m_pTextures[i] ) ) )
m_pTextures[i] = NULL;
}
}
}
SAFE_RELEASE( pAdjacencyBuffer );
SAFE_RELEASE( pMtrlBuffer );
return S_OK;
}
//-----------------------------------------------------------------------------
// Name:
// Desc:
//-----------------------------------------------------------------------------
HRESULT CD3DMesh::SetFVF( LPDIRECT3DDEVICE8 pd3dDevice, DWORD dwFVF )
{
LPD3DXMESH pTempSysMemMesh = NULL;
LPD3DXMESH pTempLocalMesh = NULL;
if( m_pSysMemMesh )
{
if( FAILED( m_pSysMemMesh->CloneMeshFVF( D3DXMESH_SYSTEMMEM, dwFVF,
pd3dDevice, &pTempSysMemMesh ) ) )
return E_FAIL;
}
if( m_pLocalMesh )
{
if( FAILED( m_pLocalMesh->CloneMeshFVF( 0L, dwFVF, pd3dDevice,
&pTempLocalMesh ) ) )
{
SAFE_RELEASE( pTempSysMemMesh );
return E_FAIL;
}
}
SAFE_RELEASE( m_pSysMemMesh );
SAFE_RELEASE( m_pLocalMesh );
if( pTempSysMemMesh ) m_pSysMemMesh = pTempSysMemMesh;
if( pTempLocalMesh ) m_pLocalMesh = pTempLocalMesh;
// Compute normals in case the meshes have them
if( m_pSysMemMesh )
D3DXComputeNormals( m_pSysMemMesh, NULL );
if( m_pLocalMesh )
D3DXComputeNormals( m_pLocalMesh, NULL );
return S_OK;
}
//-----------------------------------------------------------------------------
// Name:
// Desc:
//-----------------------------------------------------------------------------
HRESULT CD3DMesh::RestoreDeviceObjects( LPDIRECT3DDEVICE8 pd3dDevice )
{
if( NULL == m_pSysMemMesh )
return E_FAIL;
// Make a local memory version of the mesh. Note: because we are passing in
// no flags, the default behavior is to clone into local memory.
if( FAILED( m_pSysMemMesh->CloneMeshFVF( 0L, m_pSysMemMesh->GetFVF(),
pd3dDevice, &m_pLocalMesh ) ) )
return E_FAIL;
return S_OK;
}
//-----------------------------------------------------------------------------
// Name:
// Desc:
//-----------------------------------------------------------------------------
HRESULT CD3DMesh::InvalidateDeviceObjects()
{
SAFE_RELEASE( m_pLocalMesh );
return S_OK;
}
//-----------------------------------------------------------------------------
// Name:
// Desc:
//-----------------------------------------------------------------------------
HRESULT CD3DMesh::Destroy()
{
InvalidateDeviceObjects();
for( UINT i=0; i<m_dwNumMaterials; i++ )
SAFE_RELEASE( m_pTextures[i] );
SAFE_DELETE_ARRAY( m_pTextures );
SAFE_DELETE_ARRAY( m_pMaterials );
SAFE_RELEASE( m_pSysMemMesh );
m_dwNumMaterials = 0L;
return S_OK;
}
//-----------------------------------------------------------------------------
// Name:
// Desc:
//-----------------------------------------------------------------------------
HRESULT CD3DMesh::Render( LPDIRECT3DDEVICE8 pd3dDevice, BOOL bDrawOpaqueSubsets,
BOOL bDrawAlphaSubsets )
{
if( NULL == m_pLocalMesh )
return E_FAIL;
// Frist, draw the subsets without alpha
if( bDrawOpaqueSubsets )
{
for( DWORD i=0; i<m_dwNumMaterials; i++ )
{
if( m_bUseMaterials )
{
if( m_pMaterials[i].Diffuse.a < 1.0f )
continue;
pd3dDevice->SetMaterial( &m_pMaterials[i] );
pd3dDevice->SetTexture( 0, m_pTextures[i] );
}
m_pLocalMesh->DrawSubset( i );
}
}
// Then, draw the subsets with alpha
if( bDrawAlphaSubsets && m_bUseMaterials )
{
for( DWORD i=0; i<m_dwNumMaterials; i++ )
{
if( m_pMaterials[i].Diffuse.a == 1.0f )
continue;
// Set the material and texture
pd3dDevice->SetMaterial( &m_pMaterials[i] );
pd3dDevice->SetTexture( 0, m_pTextures[i] );
m_pLocalMesh->DrawSubset( i );
}
}
return S_OK;
}
//-----------------------------------------------------------------------------
// Name:
// Desc:
//-----------------------------------------------------------------------------
CD3DFrame::CD3DFrame( TCHAR* strName )
{
_tcscpy( m_strName, strName );
D3DXMatrixIdentity( &m_mat );
m_pMesh = NULL;
m_pChild = NULL;
m_pNext = NULL;
}
//-----------------------------------------------------------------------------
// Name:
// Desc:
//-----------------------------------------------------------------------------
CD3DFrame::~CD3DFrame()
{
SAFE_DELETE( m_pChild );
SAFE_DELETE( m_pNext );
}
//-----------------------------------------------------------------------------
// Name:
// Desc:
//-----------------------------------------------------------------------------
BOOL CD3DFrame::EnumMeshes( BOOL (*EnumMeshCB)(CD3DMesh*,VOID*),
VOID* pContext )
{
if( m_pMesh )
EnumMeshCB( m_pMesh, pContext );
if( m_pChild )
m_pChild->EnumMeshes( EnumMeshCB, pContext );
if( m_pNext )
m_pNext->EnumMeshes( EnumMeshCB, pContext );
return TRUE;
}
//-----------------------------------------------------------------------------
// Name:
// Desc:
//-----------------------------------------------------------------------------
CD3DMesh* CD3DFrame::FindMesh( TCHAR* strMeshName )
{
CD3DMesh* pMesh;
if( m_pMesh )
if( !lstrcmpi( m_pMesh->m_strName, strMeshName ) )
return m_pMesh;
if( m_pChild )
if( NULL != ( pMesh = m_pChild->FindMesh( strMeshName ) ) )
return pMesh;
if( m_pNext )
if( NULL != ( pMesh = m_pNext->FindMesh( strMeshName ) ) )
return pMesh;
return NULL;
}
//-----------------------------------------------------------------------------
// Name:
// Desc:
//-----------------------------------------------------------------------------
CD3DFrame* CD3DFrame::FindFrame( TCHAR* strFrameName )
{
CD3DFrame* pFrame;
if( !lstrcmpi( m_strName, strFrameName ) )
return this;
if( m_pChild )
if( NULL != ( pFrame = m_pChild->FindFrame( strFrameName ) ) )
return pFrame;
if( m_pNext )
if( NULL != ( pFrame = m_pNext->FindFrame( strFrameName ) ) )
return pFrame;
return NULL;
}
//-----------------------------------------------------------------------------
// Name:
// Desc:
//-----------------------------------------------------------------------------
HRESULT CD3DFrame::Destroy()
{
if( m_pMesh ) m_pMesh->Destroy();
if( m_pChild ) m_pChild->Destroy();
if( m_pNext ) m_pNext->Destroy();
SAFE_DELETE( m_pMesh );
SAFE_DELETE( m_pNext );
SAFE_DELETE( m_pChild );
return S_OK;
}
//-----------------------------------------------------------------------------
// Name:
// Desc:
//-----------------------------------------------------------------------------
HRESULT CD3DFrame::RestoreDeviceObjects( LPDIRECT3DDEVICE8 pd3dDevice )
{
if( m_pMesh ) m_pMesh->RestoreDeviceObjects( pd3dDevice );
if( m_pChild ) m_pChild->RestoreDeviceObjects( pd3dDevice );
if( m_pNext ) m_pNext->RestoreDeviceObjects( pd3dDevice );
return S_OK;
}
//-----------------------------------------------------------------------------
// Name:
// Desc:
//-----------------------------------------------------------------------------
HRESULT CD3DFrame::InvalidateDeviceObjects()
{
if( m_pMesh ) m_pMesh->InvalidateDeviceObjects();
if( m_pChild ) m_pChild->InvalidateDeviceObjects();
if( m_pNext ) m_pNext->InvalidateDeviceObjects();
return S_OK;
}
//-----------------------------------------------------------------------------
// Name:
// Desc:
//-----------------------------------------------------------------------------
HRESULT CD3DFrame::Render( LPDIRECT3DDEVICE8 pd3dDevice, BOOL bDrawOpaqueSubsets,
BOOL bDrawAlphaSubsets, D3DXMATRIX* pmatWorldMatrix )
{
// For pure devices, specify the world transform. If the world transform is not
// specified on pure devices, this function will fail.
D3DXMATRIX matSavedWorld, matWorld;
if ( NULL == pmatWorldMatrix )
pd3dDevice->GetTransform( D3DTS_WORLD, &matSavedWorld );
else
matSavedWorld = *pmatWorldMatrix;
D3DXMatrixMultiply( &matWorld, &m_mat, &matSavedWorld );
pd3dDevice->SetTransform( D3DTS_WORLD, &matWorld );
if( m_pMesh )
m_pMesh->Render( pd3dDevice, bDrawOpaqueSubsets, bDrawAlphaSubsets );
if( m_pChild )
m_pChild->Render( pd3dDevice, bDrawOpaqueSubsets, bDrawAlphaSubsets, &matWorld );
pd3dDevice->SetTransform( D3DTS_WORLD, &matSavedWorld );
if( m_pNext )
m_pNext->Render( pd3dDevice, bDrawOpaqueSubsets, bDrawAlphaSubsets, &matSavedWorld );
return S_OK;
}
//-----------------------------------------------------------------------------
// Name:
// Desc:
//-----------------------------------------------------------------------------
HRESULT CD3DFile::LoadFrame( LPDIRECT3DDEVICE8 pd3dDevice,
LPDIRECTXFILEDATA pFileData,
CD3DFrame* pParentFrame )
{
LPDIRECTXFILEDATA pChildData = NULL;
LPDIRECTXFILEOBJECT pChildObj = NULL;
const GUID* pGUID;
DWORD cbSize;
CD3DFrame* pCurrentFrame;
HRESULT hr;
// Get the type of the object
if( FAILED( hr = pFileData->GetType( &pGUID ) ) )
return hr;
if( *pGUID == TID_D3DRMMesh )
{
hr = LoadMesh( pd3dDevice, pFileData, pParentFrame );
if( FAILED(hr) )
return hr;
}
if( *pGUID == TID_D3DRMFrameTransformMatrix )
{
D3DXMATRIX* pmatMatrix;
hr = pFileData->GetData( NULL, &cbSize, (VOID**)&pmatMatrix );
if( FAILED(hr) )
return hr;
// Update the parent's matrix with the new one
pParentFrame->SetMatrix( pmatMatrix );
}
if( *pGUID == TID_D3DRMFrame )
{
// Get the frame name
CHAR strAnsiName[512] = "";
TCHAR strName[MAX_PATH];
DWORD dwNameLength;
pFileData->GetName( NULL, &dwNameLength );
if( dwNameLength > 0 )
pFileData->GetName( strAnsiName, &dwNameLength );
DXUtil_ConvertAnsiStringToGeneric( strName, strAnsiName );
// Create the frame
pCurrentFrame = new CD3DFrame( strName );
pCurrentFrame->m_pNext = pParentFrame->m_pChild;
pParentFrame->m_pChild = pCurrentFrame;
// Enumerate child objects
while( SUCCEEDED( pFileData->GetNextObject( &pChildObj ) ) )
{
// Query the child for its FileData
hr = pChildObj->QueryInterface( IID_IDirectXFileData,
(VOID**)&pChildData );
if( SUCCEEDED(hr) )
{
hr = LoadFrame( pd3dDevice, pChildData, pCurrentFrame );
pChildData->Release();
}
pChildObj->Release();
if( FAILED(hr) )
return hr;
}
}
return S_OK;
}
//-----------------------------------------------------------------------------
// Name:
// Desc:
//-----------------------------------------------------------------------------
HRESULT CD3DFile::LoadMesh( LPDIRECT3DDEVICE8 pd3dDevice,
LPDIRECTXFILEDATA pFileData,
CD3DFrame* pParentFrame )
{
// Currently only allowing one mesh per frame
if( pParentFrame->m_pMesh )
return E_FAIL;
// Get the mesh name
CHAR strAnsiName[512] = {0};
TCHAR strName[MAX_PATH];
DWORD dwNameLength;
pFileData->GetName( NULL, &dwNameLength );
if( dwNameLength > 0 )
pFileData->GetName( strAnsiName, &dwNameLength );
DXUtil_ConvertAnsiStringToGeneric( strName, strAnsiName );
// Create the mesh
pParentFrame->m_pMesh = new CD3DMesh( strName );
pParentFrame->m_pMesh->Create( pd3dDevice, pFileData );
return S_OK;
}
//-----------------------------------------------------------------------------
// Name:
// Desc:
//-----------------------------------------------------------------------------
HRESULT CD3DFile::CreateFromResource( LPDIRECT3DDEVICE8 pd3dDevice, TCHAR* strResource, TCHAR* strType )
{
LPDIRECTXFILE pDXFile = NULL;
LPDIRECTXFILEENUMOBJECT pEnumObj = NULL;
LPDIRECTXFILEDATA pFileData = NULL;
HRESULT hr;
// Create a x file object
if( FAILED( hr = DirectXFileCreate( &pDXFile ) ) )
return E_FAIL;
// Register templates for d3drm and patch extensions.
if( FAILED( hr = pDXFile->RegisterTemplates( (VOID*)D3DRM_XTEMPLATES,
D3DRM_XTEMPLATE_BYTES ) ) )
{
pDXFile->Release();
return E_FAIL;
}
CHAR strTypeAnsi[MAX_PATH];
DXUtil_ConvertGenericStringToAnsi( strTypeAnsi, strType );
DXFILELOADRESOURCE dxlr;
dxlr.hModule = NULL;
dxlr.lpName = strResource;
dxlr.lpType = (TCHAR*) strTypeAnsi;
// Create enum object
hr = pDXFile->CreateEnumObject( (VOID*)&dxlr, DXFILELOAD_FROMRESOURCE,
&pEnumObj );
if( FAILED(hr) )
{
pDXFile->Release();
return hr;
}
// Enumerate top level objects (which are always frames)
while( SUCCEEDED( pEnumObj->GetNextDataObject( &pFileData ) ) )
{
hr = LoadFrame( pd3dDevice, pFileData, this );
pFileData->Release();
if( FAILED(hr) )
{
pEnumObj->Release();
pDXFile->Release();
return E_FAIL;
}
}
SAFE_RELEASE( pFileData );
SAFE_RELEASE( pEnumObj );
SAFE_RELEASE( pDXFile );
return S_OK;
}
//-----------------------------------------------------------------------------
// Name:
// Desc:
//-----------------------------------------------------------------------------
HRESULT CD3DFile::Create( LPDIRECT3DDEVICE8 pd3dDevice, TCHAR* strFilename )
{
LPDIRECTXFILE pDXFile = NULL;
LPDIRECTXFILEENUMOBJECT pEnumObj = NULL;
LPDIRECTXFILEDATA pFileData = NULL;
HRESULT hr;
// Create a x file object
if( FAILED( hr = DirectXFileCreate( &pDXFile ) ) )
return E_FAIL;
// Register templates for d3drm and patch extensions.
if( FAILED( hr = pDXFile->RegisterTemplates( (VOID*)D3DRM_XTEMPLATES,
D3DRM_XTEMPLATE_BYTES ) ) )
{
pDXFile->Release();
return E_FAIL;
}
// Find the path to the file, and convert it to ANSI (for the D3DXOF API)
TCHAR strPath[MAX_PATH];
CHAR strPathANSI[MAX_PATH];
DXUtil_FindMediaFile( strPath, strFilename );
DXUtil_ConvertGenericStringToAnsi( strPathANSI, strPath );
// Create enum object
hr = pDXFile->CreateEnumObject( (VOID*)strPathANSI, DXFILELOAD_FROMFILE,
&pEnumObj );
if( FAILED(hr) )
{
pDXFile->Release();
return hr;
}
// Enumerate top level objects (which are always frames)
while( SUCCEEDED( pEnumObj->GetNextDataObject( &pFileData ) ) )
{
hr = LoadFrame( pd3dDevice, pFileData, this );
pFileData->Release();
if( FAILED(hr) )
{
pEnumObj->Release();
pDXFile->Release();
return E_FAIL;
}
}
SAFE_RELEASE( pFileData );
SAFE_RELEASE( pEnumObj );
SAFE_RELEASE( pDXFile );
return S_OK;
}
//-----------------------------------------------------------------------------
// Name:
// Desc:
//-----------------------------------------------------------------------------
HRESULT CD3DFile::Render( LPDIRECT3DDEVICE8 pd3dDevice, D3DXMATRIX* pmatWorldMatrix )
{
// For pure devices, specify the world transform. If the world transform is not
// specified on pure devices, this function will fail.
// Set up the world transformation
D3DXMATRIX matSavedWorld, matWorld;
if ( NULL == pmatWorldMatrix )
pd3dDevice->GetTransform( D3DTS_WORLD, &matSavedWorld );
else
matSavedWorld = *pmatWorldMatrix;
D3DXMatrixMultiply( &matWorld, &matSavedWorld, &m_mat );
pd3dDevice->SetTransform( D3DTS_WORLD, &matWorld );
// Render opaque subsets in the meshes
if( m_pChild )
m_pChild->Render( pd3dDevice, TRUE, FALSE, &matWorld );
// Enable alpha blending
pd3dDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, TRUE );
pd3dDevice->SetRenderState( D3DRS_SRCBLEND, D3DBLEND_SRCALPHA );
pd3dDevice->SetRenderState( D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA );
// Render alpha subsets in the meshes
if( m_pChild )
m_pChild->Render( pd3dDevice, FALSE, TRUE, &matWorld );
// Restore state
pd3dDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, FALSE );
pd3dDevice->SetTransform( D3DTS_WORLD, &matSavedWorld );
return S_OK;
}

View File

@@ -0,0 +1,674 @@
//-----------------------------------------------------------------------------
// File: D3DFont.cpp
//
// Desc: Texture-based font class
//
// Copyright (c) 1999-2001 Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#define STRICT
#include <stdio.h>
#include <tchar.h>
#include <D3DX8.h>
#include "D3DFont.h"
#include "D3DUtil.h"
#include "DXUtil.h"
//-----------------------------------------------------------------------------
// Custom vertex types for rendering text
//-----------------------------------------------------------------------------
#define MAX_NUM_VERTICES 50*6
struct FONT2DVERTEX { D3DXVECTOR4 p; DWORD color; FLOAT tu, tv; };
struct FONT3DVERTEX { D3DXVECTOR3 p; D3DXVECTOR3 n; FLOAT tu, tv; };
#define D3DFVF_FONT2DVERTEX (D3DFVF_XYZRHW|D3DFVF_DIFFUSE|D3DFVF_TEX1)
#define D3DFVF_FONT3DVERTEX (D3DFVF_XYZ|D3DFVF_NORMAL|D3DFVF_TEX1)
inline FONT2DVERTEX InitFont2DVertex( const D3DXVECTOR4& p, D3DCOLOR color,
FLOAT tu, FLOAT tv )
{
FONT2DVERTEX v; v.p = p; v.color = color; v.tu = tu; v.tv = tv;
return v;
}
inline FONT3DVERTEX InitFont3DVertex( const D3DXVECTOR3& p, const D3DXVECTOR3& n,
FLOAT tu, FLOAT tv )
{
FONT3DVERTEX v; v.p = p; v.n = n; v.tu = tu; v.tv = tv;
return v;
}
//-----------------------------------------------------------------------------
// Name: CD3DFont()
// Desc: Font class constructor
//-----------------------------------------------------------------------------
CD3DFont::CD3DFont( TCHAR* strFontName, DWORD dwHeight, DWORD dwFlags )
{
_tcscpy( m_strFontName, strFontName );
m_dwFontHeight = dwHeight;
m_dwFontFlags = dwFlags;
m_pd3dDevice = NULL;
m_pTexture = NULL;
m_pVB = NULL;
m_dwSavedStateBlock = 0L;
m_dwDrawTextStateBlock = 0L;
}
//-----------------------------------------------------------------------------
// Name: ~CD3DFont()
// Desc: Font class destructor
//-----------------------------------------------------------------------------
CD3DFont::~CD3DFont()
{
InvalidateDeviceObjects();
DeleteDeviceObjects();
}
//-----------------------------------------------------------------------------
// Name: InitDeviceObjects()
// Desc: Initializes device-dependent objects, including the vertex buffer used
// for rendering text and the texture map which stores the font image.
//-----------------------------------------------------------------------------
HRESULT CD3DFont::InitDeviceObjects( LPDIRECT3DDEVICE8 pd3dDevice )
{
HRESULT hr;
// Keep a local copy of the device
m_pd3dDevice = pd3dDevice;
// Establish the font and texture size
m_fTextScale = 1.0f; // Draw fonts into texture without scaling
// Large fonts need larger textures
if( m_dwFontHeight > 40 )
m_dwTexWidth = m_dwTexHeight = 1024;
else if( m_dwFontHeight > 20 )
m_dwTexWidth = m_dwTexHeight = 512;
else
m_dwTexWidth = m_dwTexHeight = 256;
// If requested texture is too big, use a smaller texture and smaller font,
// and scale up when rendering.
D3DCAPS8 d3dCaps;
m_pd3dDevice->GetDeviceCaps( &d3dCaps );
if( m_dwTexWidth > d3dCaps.MaxTextureWidth )
{
m_fTextScale = (FLOAT)d3dCaps.MaxTextureWidth / (FLOAT)m_dwTexWidth;
m_dwTexWidth = m_dwTexHeight = d3dCaps.MaxTextureWidth;
}
// Create a new texture for the font
hr = m_pd3dDevice->CreateTexture( m_dwTexWidth, m_dwTexHeight, 1,
0, D3DFMT_A4R4G4B4,
D3DPOOL_MANAGED, &m_pTexture );
if( FAILED(hr) )
return hr;
// Prepare to create a bitmap
DWORD* pBitmapBits;
BITMAPINFO bmi;
ZeroMemory( &bmi.bmiHeader, sizeof(BITMAPINFOHEADER) );
bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bmi.bmiHeader.biWidth = (int)m_dwTexWidth;
bmi.bmiHeader.biHeight = -(int)m_dwTexHeight;
bmi.bmiHeader.biPlanes = 1;
bmi.bmiHeader.biCompression = BI_RGB;
bmi.bmiHeader.biBitCount = 32;
// Create a DC and a bitmap for the font
HDC hDC = CreateCompatibleDC( NULL );
HBITMAP hbmBitmap = CreateDIBSection( hDC, &bmi, DIB_RGB_COLORS,
(VOID**)&pBitmapBits, NULL, 0 );
SetMapMode( hDC, MM_TEXT );
// Create a font. By specifying ANTIALIASED_QUALITY, we might get an
// antialiased font, but this is not guaranteed.
INT nHeight = -MulDiv( m_dwFontHeight,
(INT)(GetDeviceCaps(hDC, LOGPIXELSY) * m_fTextScale), 72 );
DWORD dwBold = (m_dwFontFlags&D3DFONT_BOLD) ? FW_BOLD : FW_NORMAL;
DWORD dwItalic = (m_dwFontFlags&D3DFONT_ITALIC) ? TRUE : FALSE;
HFONT hFont = CreateFont( nHeight, 0, 0, 0, dwBold, dwItalic,
FALSE, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS,
CLIP_DEFAULT_PRECIS, ANTIALIASED_QUALITY,
VARIABLE_PITCH, m_strFontName );
if( NULL==hFont )
return E_FAIL;
SelectObject( hDC, hbmBitmap );
SelectObject( hDC, hFont );
// Set text properties
SetTextColor( hDC, RGB(255,255,255) );
SetBkColor( hDC, 0x00000000 );
SetTextAlign( hDC, TA_TOP );
// Loop through all printable character and output them to the bitmap..
// Meanwhile, keep track of the corresponding tex coords for each character.
DWORD x = 0;
DWORD y = 0;
TCHAR str[2] = _T("x");
SIZE size;
for( TCHAR c=32; c<127; c++ )
{
str[0] = c;
GetTextExtentPoint32( hDC, str, 1, &size );
if( (DWORD)(x+size.cx+1) > m_dwTexWidth )
{
x = 0;
y += size.cy+1;
}
ExtTextOut( hDC, x+0, y+0, ETO_OPAQUE, NULL, str, 1, NULL );
m_fTexCoords[c-32][0] = ((FLOAT)(x+0))/m_dwTexWidth;
m_fTexCoords[c-32][1] = ((FLOAT)(y+0))/m_dwTexHeight;
m_fTexCoords[c-32][2] = ((FLOAT)(x+0+size.cx))/m_dwTexWidth;
m_fTexCoords[c-32][3] = ((FLOAT)(y+0+size.cy))/m_dwTexHeight;
x += size.cx+1;
}
// Lock the surface and write the alpha values for the set pixels
D3DLOCKED_RECT d3dlr;
m_pTexture->LockRect( 0, &d3dlr, 0, 0 );
BYTE* pDstRow = (BYTE*)d3dlr.pBits;
WORD* pDst16;
BYTE bAlpha; // 4-bit measure of pixel intensity
for( y=0; y < m_dwTexHeight; y++ )
{
pDst16 = (WORD*)pDstRow;
for( x=0; x < m_dwTexWidth; x++ )
{
bAlpha = (BYTE)((pBitmapBits[m_dwTexWidth*y + x] & 0xff) >> 4);
if (bAlpha > 0)
{
*pDst16++ = (bAlpha << 12) | 0x0fff;
}
else
{
*pDst16++ = 0x0000;
}
}
pDstRow += d3dlr.Pitch;
}
// Done updating texture, so clean up used objects
m_pTexture->UnlockRect(0);
DeleteObject( hbmBitmap );
DeleteDC( hDC );
DeleteObject( hFont );
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: RestoreDeviceObjects()
// Desc:
//-----------------------------------------------------------------------------
HRESULT CD3DFont::RestoreDeviceObjects()
{
HRESULT hr;
// Create vertex buffer for the letters
if( FAILED( hr = m_pd3dDevice->CreateVertexBuffer( MAX_NUM_VERTICES*sizeof(FONT2DVERTEX),
D3DUSAGE_WRITEONLY | D3DUSAGE_DYNAMIC, 0,
D3DPOOL_DEFAULT, &m_pVB ) ) )
{
return hr;
}
// Create the state blocks for rendering text
for( UINT which=0; which<2; which++ )
{
m_pd3dDevice->BeginStateBlock();
m_pd3dDevice->SetTexture( 0, m_pTexture );
if ( D3DFONT_ZENABLE & m_dwFontFlags )
m_pd3dDevice->SetRenderState( D3DRS_ZENABLE, TRUE );
else
m_pd3dDevice->SetRenderState( D3DRS_ZENABLE, FALSE );
m_pd3dDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, TRUE );
m_pd3dDevice->SetRenderState( D3DRS_SRCBLEND, D3DBLEND_SRCALPHA );
m_pd3dDevice->SetRenderState( D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA );
m_pd3dDevice->SetRenderState( D3DRS_ALPHATESTENABLE, TRUE );
m_pd3dDevice->SetRenderState( D3DRS_ALPHAREF, 0x08 );
m_pd3dDevice->SetRenderState( D3DRS_ALPHAFUNC, D3DCMP_GREATEREQUAL );
m_pd3dDevice->SetRenderState( D3DRS_FILLMODE, D3DFILL_SOLID );
m_pd3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_CCW );
m_pd3dDevice->SetRenderState( D3DRS_STENCILENABLE, FALSE );
m_pd3dDevice->SetRenderState( D3DRS_CLIPPING, TRUE );
m_pd3dDevice->SetRenderState( D3DRS_EDGEANTIALIAS, FALSE );
m_pd3dDevice->SetRenderState( D3DRS_CLIPPLANEENABLE, FALSE );
m_pd3dDevice->SetRenderState( D3DRS_VERTEXBLEND, FALSE );
m_pd3dDevice->SetRenderState( D3DRS_INDEXEDVERTEXBLENDENABLE, FALSE );
m_pd3dDevice->SetRenderState( D3DRS_FOGENABLE, FALSE );
m_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_MODULATE );
m_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
m_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE );
m_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_MODULATE );
m_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE );
m_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE );
m_pd3dDevice->SetTextureStageState( 0, D3DTSS_MINFILTER, D3DTEXF_POINT );
m_pd3dDevice->SetTextureStageState( 0, D3DTSS_MAGFILTER, D3DTEXF_POINT );
m_pd3dDevice->SetTextureStageState( 0, D3DTSS_MIPFILTER, D3DTEXF_NONE );
m_pd3dDevice->SetTextureStageState( 0, D3DTSS_TEXCOORDINDEX, 0 );
m_pd3dDevice->SetTextureStageState( 0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_DISABLE );
m_pd3dDevice->SetTextureStageState( 1, D3DTSS_COLOROP, D3DTOP_DISABLE );
m_pd3dDevice->SetTextureStageState( 1, D3DTSS_ALPHAOP, D3DTOP_DISABLE );
if( which==0 )
m_pd3dDevice->EndStateBlock( &m_dwSavedStateBlock );
else
m_pd3dDevice->EndStateBlock( &m_dwDrawTextStateBlock );
}
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: InvalidateDeviceObjects()
// Desc: Destroys all device-dependent objects
//-----------------------------------------------------------------------------
HRESULT CD3DFont::InvalidateDeviceObjects()
{
SAFE_RELEASE( m_pVB );
// Delete the state blocks
if( m_pd3dDevice )
{
if( m_dwSavedStateBlock )
m_pd3dDevice->DeleteStateBlock( m_dwSavedStateBlock );
if( m_dwDrawTextStateBlock )
m_pd3dDevice->DeleteStateBlock( m_dwDrawTextStateBlock );
}
m_dwSavedStateBlock = 0L;
m_dwDrawTextStateBlock = 0L;
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: DeleteDeviceObjects()
// Desc: Destroys all device-dependent objects
//-----------------------------------------------------------------------------
HRESULT CD3DFont::DeleteDeviceObjects()
{
SAFE_RELEASE( m_pTexture );
m_pd3dDevice = NULL;
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: GetTextExtent()
// Desc: Get the dimensions of a text string
//-----------------------------------------------------------------------------
HRESULT CD3DFont::GetTextExtent( TCHAR* strText, SIZE* pSize )
{
if( NULL==strText || NULL==pSize )
return E_FAIL;
FLOAT fRowWidth = 0.0f;
FLOAT fRowHeight = (m_fTexCoords[0][3]-m_fTexCoords[0][1])*m_dwTexHeight;
FLOAT fWidth = 0.0f;
FLOAT fHeight = fRowHeight;
while( *strText )
{
TCHAR c = *strText++;
if( c == _T('\n') )
{
fRowWidth = 0.0f;
fHeight += fRowHeight;
}
if( c < _T(' ') )
continue;
FLOAT tx1 = m_fTexCoords[c-32][0];
FLOAT tx2 = m_fTexCoords[c-32][2];
fRowWidth += (tx2-tx1)*m_dwTexWidth;
if( fRowWidth > fWidth )
fWidth = fRowWidth;
}
pSize->cx = (int)fWidth;
pSize->cy = (int)fHeight;
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: DrawTextScaled()
// Desc: Draws scaled 2D text. Note that x and y are in viewport coordinates
// (ranging from -1 to +1). fXScale and fYScale are the size fraction
// relative to the entire viewport. For example, a fXScale of 0.25 is
// 1/8th of the screen width. This allows you to output text at a fixed
// fraction of the viewport, even if the screen or window size changes.
//-----------------------------------------------------------------------------
HRESULT CD3DFont::DrawTextScaled( FLOAT x, FLOAT y, FLOAT z,
FLOAT fXScale, FLOAT fYScale, DWORD dwColor,
TCHAR* strText, DWORD dwFlags )
{
if( m_pd3dDevice == NULL )
return E_FAIL;
// Set up renderstate
m_pd3dDevice->CaptureStateBlock( m_dwSavedStateBlock );
m_pd3dDevice->ApplyStateBlock( m_dwDrawTextStateBlock );
m_pd3dDevice->SetVertexShader( D3DFVF_FONT2DVERTEX );
m_pd3dDevice->SetPixelShader( NULL );
m_pd3dDevice->SetStreamSource( 0, m_pVB, sizeof(FONT2DVERTEX) );
// Set filter states
if( dwFlags & D3DFONT_FILTERED )
{
m_pd3dDevice->SetTextureStageState( 0, D3DTSS_MINFILTER, D3DTEXF_LINEAR );
m_pd3dDevice->SetTextureStageState( 0, D3DTSS_MAGFILTER, D3DTEXF_LINEAR );
}
D3DVIEWPORT8 vp;
m_pd3dDevice->GetViewport( &vp );
FLOAT sx = (x+1.0f)*vp.Width/2;
FLOAT sy = (y+1.0f)*vp.Height/2;
FLOAT sz = z;
FLOAT rhw = 1.0f;
FLOAT fStartX = sx;
FLOAT fLineHeight = ( m_fTexCoords[0][3] - m_fTexCoords[0][1] ) * m_dwTexHeight;
// Fill vertex buffer
FONT2DVERTEX* pVertices;
DWORD dwNumTriangles = 0L;
m_pVB->Lock( 0, 0, (BYTE**)&pVertices, D3DLOCK_DISCARD );
while( *strText )
{
TCHAR c = *strText++;
if( c == _T('\n') )
{
sx = fStartX;
sy += fYScale*vp.Height;
}
if( c < _T(' ') )
continue;
FLOAT tx1 = m_fTexCoords[c-32][0];
FLOAT ty1 = m_fTexCoords[c-32][1];
FLOAT tx2 = m_fTexCoords[c-32][2];
FLOAT ty2 = m_fTexCoords[c-32][3];
FLOAT w = (tx2-tx1)*m_dwTexWidth;
FLOAT h = (ty2-ty1)*m_dwTexHeight;
w *= (fXScale*vp.Width)/fLineHeight;
h *= (fYScale*vp.Height)/fLineHeight;
if( c != _T(' ') )
{
*pVertices++ = InitFont2DVertex( D3DXVECTOR4(sx+0-0.5f,sy+h-0.5f,sz,rhw), dwColor, tx1, ty2 );
*pVertices++ = InitFont2DVertex( D3DXVECTOR4(sx+0-0.5f,sy+0-0.5f,sz,rhw), dwColor, tx1, ty1 );
*pVertices++ = InitFont2DVertex( D3DXVECTOR4(sx+w-0.5f,sy+h-0.5f,sz,rhw), dwColor, tx2, ty2 );
*pVertices++ = InitFont2DVertex( D3DXVECTOR4(sx+w-0.5f,sy+0-0.5f,sz,rhw), dwColor, tx2, ty1 );
*pVertices++ = InitFont2DVertex( D3DXVECTOR4(sx+w-0.5f,sy+h-0.5f,sz,rhw), dwColor, tx2, ty2 );
*pVertices++ = InitFont2DVertex( D3DXVECTOR4(sx+0-0.5f,sy+0-0.5f,sz,rhw), dwColor, tx1, ty1 );
dwNumTriangles += 2;
if( dwNumTriangles*3 > (MAX_NUM_VERTICES-6) )
{
// Unlock, render, and relock the vertex buffer
m_pVB->Unlock();
m_pd3dDevice->DrawPrimitive( D3DPT_TRIANGLELIST, 0, dwNumTriangles );
m_pVB->Lock( 0, 0, (BYTE**)&pVertices, D3DLOCK_DISCARD );
dwNumTriangles = 0L;
}
}
sx += w;
}
// Unlock and render the vertex buffer
m_pVB->Unlock();
if( dwNumTriangles > 0 )
m_pd3dDevice->DrawPrimitive( D3DPT_TRIANGLELIST, 0, dwNumTriangles );
// Restore the modified renderstates
m_pd3dDevice->ApplyStateBlock( m_dwSavedStateBlock );
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: DrawText()
// Desc: Draws 2D text
//-----------------------------------------------------------------------------
HRESULT CD3DFont::DrawText( FLOAT sx, FLOAT sy, DWORD dwColor,
TCHAR* strText, DWORD dwFlags )
{
if( m_pd3dDevice == NULL )
return E_FAIL;
// Setup renderstate
m_pd3dDevice->CaptureStateBlock( m_dwSavedStateBlock );
m_pd3dDevice->ApplyStateBlock( m_dwDrawTextStateBlock );
m_pd3dDevice->SetVertexShader( D3DFVF_FONT2DVERTEX );
m_pd3dDevice->SetPixelShader( NULL );
m_pd3dDevice->SetStreamSource( 0, m_pVB, sizeof(FONT2DVERTEX) );
// Set filter states
if( dwFlags & D3DFONT_FILTERED )
{
m_pd3dDevice->SetTextureStageState( 0, D3DTSS_MINFILTER, D3DTEXF_LINEAR );
m_pd3dDevice->SetTextureStageState( 0, D3DTSS_MAGFILTER, D3DTEXF_LINEAR );
}
FLOAT fStartX = sx;
// Fill vertex buffer
FONT2DVERTEX* pVertices = NULL;
DWORD dwNumTriangles = 0;
m_pVB->Lock( 0, 0, (BYTE**)&pVertices, D3DLOCK_DISCARD );
while( *strText )
{
TCHAR c = *strText++;
if( c == _T('\n') )
{
sx = fStartX;
sy += (m_fTexCoords[0][3]-m_fTexCoords[0][1])*m_dwTexHeight;
}
if( c < _T(' ') )
continue;
FLOAT tx1 = m_fTexCoords[c-32][0];
FLOAT ty1 = m_fTexCoords[c-32][1];
FLOAT tx2 = m_fTexCoords[c-32][2];
FLOAT ty2 = m_fTexCoords[c-32][3];
FLOAT w = (tx2-tx1) * m_dwTexWidth / m_fTextScale;
FLOAT h = (ty2-ty1) * m_dwTexHeight / m_fTextScale;
if( c != _T(' ') )
{
*pVertices++ = InitFont2DVertex( D3DXVECTOR4(sx+0-0.5f,sy+h-0.5f,0.9f,1.0f), dwColor, tx1, ty2 );
*pVertices++ = InitFont2DVertex( D3DXVECTOR4(sx+0-0.5f,sy+0-0.5f,0.9f,1.0f), dwColor, tx1, ty1 );
*pVertices++ = InitFont2DVertex( D3DXVECTOR4(sx+w-0.5f,sy+h-0.5f,0.9f,1.0f), dwColor, tx2, ty2 );
*pVertices++ = InitFont2DVertex( D3DXVECTOR4(sx+w-0.5f,sy+0-0.5f,0.9f,1.0f), dwColor, tx2, ty1 );
*pVertices++ = InitFont2DVertex( D3DXVECTOR4(sx+w-0.5f,sy+h-0.5f,0.9f,1.0f), dwColor, tx2, ty2 );
*pVertices++ = InitFont2DVertex( D3DXVECTOR4(sx+0-0.5f,sy+0-0.5f,0.9f,1.0f), dwColor, tx1, ty1 );
dwNumTriangles += 2;
if( dwNumTriangles*3 > (MAX_NUM_VERTICES-6) )
{
// Unlock, render, and relock the vertex buffer
m_pVB->Unlock();
m_pd3dDevice->DrawPrimitive( D3DPT_TRIANGLELIST, 0, dwNumTriangles );
pVertices = NULL;
m_pVB->Lock( 0, 0, (BYTE**)&pVertices, D3DLOCK_DISCARD );
dwNumTriangles = 0L;
}
}
sx += w;
}
// Unlock and render the vertex buffer
m_pVB->Unlock();
if( dwNumTriangles > 0 )
m_pd3dDevice->DrawPrimitive( D3DPT_TRIANGLELIST, 0, dwNumTriangles );
// Restore the modified renderstates
m_pd3dDevice->ApplyStateBlock( m_dwSavedStateBlock );
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: Render3DText()
// Desc: Renders 3D text
//-----------------------------------------------------------------------------
HRESULT CD3DFont::Render3DText( TCHAR* strText, DWORD dwFlags )
{
if( m_pd3dDevice == NULL )
return E_FAIL;
// Setup renderstate
m_pd3dDevice->CaptureStateBlock( m_dwSavedStateBlock );
m_pd3dDevice->ApplyStateBlock( m_dwDrawTextStateBlock );
m_pd3dDevice->SetVertexShader( D3DFVF_FONT3DVERTEX );
m_pd3dDevice->SetPixelShader( NULL );
m_pd3dDevice->SetStreamSource( 0, m_pVB, sizeof(FONT3DVERTEX) );
// Set filter states
if( dwFlags & D3DFONT_FILTERED )
{
m_pd3dDevice->SetTextureStageState( 0, D3DTSS_MINFILTER, D3DTEXF_LINEAR );
m_pd3dDevice->SetTextureStageState( 0, D3DTSS_MAGFILTER, D3DTEXF_LINEAR );
}
// Position for each text element
FLOAT x = 0.0f;
FLOAT y = 0.0f;
// Center the text block at the origin
if( dwFlags & D3DFONT_CENTERED )
{
SIZE sz;
GetTextExtent( strText, &sz );
x = -(((FLOAT)sz.cx)/10.0f)/2.0f;
y = -(((FLOAT)sz.cy)/10.0f)/2.0f;
}
// Turn off culling for two-sided text
if( dwFlags & D3DFONT_TWOSIDED )
m_pd3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE );
FLOAT fStartX = x;
TCHAR c;
// Fill vertex buffer
FONT3DVERTEX* pVertices;
DWORD dwVertex = 0L;
DWORD dwNumTriangles = 0L;
m_pVB->Lock( 0, 0, (BYTE**)&pVertices, D3DLOCK_DISCARD );
while( c = *strText++ )
{
if( c == '\n' )
{
x = fStartX;
y -= (m_fTexCoords[0][3]-m_fTexCoords[0][1])*m_dwTexHeight/10.0f;
}
if( c < 32 )
continue;
FLOAT tx1 = m_fTexCoords[c-32][0];
FLOAT ty1 = m_fTexCoords[c-32][1];
FLOAT tx2 = m_fTexCoords[c-32][2];
FLOAT ty2 = m_fTexCoords[c-32][3];
FLOAT w = (tx2-tx1) * m_dwTexWidth / ( 10.0f * m_fTextScale );
FLOAT h = (ty2-ty1) * m_dwTexHeight / ( 10.0f * m_fTextScale );
if( c != _T(' ') )
{
*pVertices++ = InitFont3DVertex( D3DXVECTOR3(x+0,y+0,0), D3DXVECTOR3(0,0,-1), tx1, ty2 );
*pVertices++ = InitFont3DVertex( D3DXVECTOR3(x+0,y+h,0), D3DXVECTOR3(0,0,-1), tx1, ty1 );
*pVertices++ = InitFont3DVertex( D3DXVECTOR3(x+w,y+0,0), D3DXVECTOR3(0,0,-1), tx2, ty2 );
*pVertices++ = InitFont3DVertex( D3DXVECTOR3(x+w,y+h,0), D3DXVECTOR3(0,0,-1), tx2, ty1 );
*pVertices++ = InitFont3DVertex( D3DXVECTOR3(x+w,y+0,0), D3DXVECTOR3(0,0,-1), tx2, ty2 );
*pVertices++ = InitFont3DVertex( D3DXVECTOR3(x+0,y+h,0), D3DXVECTOR3(0,0,-1), tx1, ty1 );
dwNumTriangles += 2;
if( dwNumTriangles*3 > (MAX_NUM_VERTICES-6) )
{
// Unlock, render, and relock the vertex buffer
m_pVB->Unlock();
m_pd3dDevice->DrawPrimitive( D3DPT_TRIANGLELIST, 0, dwNumTriangles );
m_pVB->Lock( 0, 0, (BYTE**)&pVertices, D3DLOCK_DISCARD );
dwNumTriangles = 0L;
}
}
x += w;
}
// Unlock and render the vertex buffer
m_pVB->Unlock();
if( dwNumTriangles > 0 )
m_pd3dDevice->DrawPrimitive( D3DPT_TRIANGLELIST, 0, dwNumTriangles );
// Restore the modified renderstates
m_pd3dDevice->ApplyStateBlock( m_dwSavedStateBlock );
return S_OK;
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,694 @@
//-----------------------------------------------------------------------------
// File: D3DUtil.cpp
//
// Desc: Shortcut macros and functions for using DX objects
//
//
// Copyright (c) 1997-2001 Microsoft Corporation. All rights reserved
//-----------------------------------------------------------------------------
#define STRICT
#include <tchar.h>
#include <stdio.h>
#include "D3DUtil.h"
#include "DXUtil.h"
#include "D3DX8.h"
//-----------------------------------------------------------------------------
// Name: D3DUtil_InitMaterial()
// Desc: Initializes a D3DMATERIAL8 structure, setting the diffuse and ambient
// colors. It does not set emissive or specular colors.
//-----------------------------------------------------------------------------
VOID D3DUtil_InitMaterial( D3DMATERIAL8& mtrl, FLOAT r, FLOAT g, FLOAT b,
FLOAT a )
{
ZeroMemory( &mtrl, sizeof(D3DMATERIAL8) );
mtrl.Diffuse.r = mtrl.Ambient.r = r;
mtrl.Diffuse.g = mtrl.Ambient.g = g;
mtrl.Diffuse.b = mtrl.Ambient.b = b;
mtrl.Diffuse.a = mtrl.Ambient.a = a;
}
//-----------------------------------------------------------------------------
// Name: D3DUtil_InitLight()
// Desc: Initializes a D3DLIGHT structure, setting the light position. The
// diffuse color is set to white; specular and ambient are left as black.
//-----------------------------------------------------------------------------
VOID D3DUtil_InitLight( D3DLIGHT8& light, D3DLIGHTTYPE ltType,
FLOAT x, FLOAT y, FLOAT z )
{
ZeroMemory( &light, sizeof(D3DLIGHT8) );
light.Type = ltType;
light.Diffuse.r = 1.0f;
light.Diffuse.g = 1.0f;
light.Diffuse.b = 1.0f;
D3DXVec3Normalize( (D3DXVECTOR3*)&light.Direction, &D3DXVECTOR3(x, y, z) );
light.Position.x = x;
light.Position.y = y;
light.Position.z = z;
light.Range = 1000.0f;
}
//-----------------------------------------------------------------------------
// Name: D3DUtil_CreateTexture()
// Desc: Helper function to create a texture. It checks the root path first,
// then tries the DXSDK media path (as specified in the system registry).
//-----------------------------------------------------------------------------
HRESULT D3DUtil_CreateTexture( LPDIRECT3DDEVICE8 pd3dDevice, TCHAR* strTexture,
LPDIRECT3DTEXTURE8* ppTexture, D3DFORMAT d3dFormat )
{
// Get the path to the texture
TCHAR strPath[MAX_PATH];
DXUtil_FindMediaFile( strPath, strTexture );
// Create the texture using D3DX
return D3DXCreateTextureFromFileEx( pd3dDevice, strPath,
D3DX_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT, 0, d3dFormat,
D3DPOOL_MANAGED, D3DX_FILTER_TRIANGLE|D3DX_FILTER_MIRROR,
D3DX_FILTER_TRIANGLE|D3DX_FILTER_MIRROR, 0, NULL, NULL, ppTexture );
}
//-----------------------------------------------------------------------------
// Name: D3DUtil_SetColorKey()
// Desc: Changes all texels matching the colorkey to transparent, black.
//-----------------------------------------------------------------------------
HRESULT D3DUtil_SetColorKey( LPDIRECT3DTEXTURE8 pTexture, DWORD dwColorKey )
{
// Get colorkey's red, green, and blue components
DWORD r = ((dwColorKey&0x00ff0000)>>16);
DWORD g = ((dwColorKey&0x0000ff00)>>8);
DWORD b = ((dwColorKey&0x000000ff)>>0);
// Put the colorkey in the texture's native format
D3DSURFACE_DESC d3dsd;
pTexture->GetLevelDesc( 0, &d3dsd );
if( d3dsd.Format == D3DFMT_A4R4G4B4 )
dwColorKey = 0xf000 + ((r>>4)<<8) + ((g>>4)<<4) + (b>>4);
else if( d3dsd.Format == D3DFMT_A1R5G5B5 )
dwColorKey = 0x8000 + ((r>>3)<<10) + ((g>>3)<<5) + (b>>3);
else if( d3dsd.Format != D3DFMT_A8R8G8B8 )
return E_FAIL;
// Lock the texture
D3DLOCKED_RECT d3dlr;
if( FAILED( pTexture->LockRect( 0, &d3dlr, 0, 0 ) ) )
return E_FAIL;
// Scan through each pixel, looking for the colorkey to replace
for( DWORD y=0; y<d3dsd.Height; y++ )
{
for( DWORD x=0; x<d3dsd.Width; x++ )
{
if( d3dsd.Format==D3DFMT_A8R8G8B8 )
{
// Handle 32-bit formats
if( ((DWORD*)d3dlr.pBits)[d3dsd.Width*y+x] == dwColorKey )
((DWORD*)d3dlr.pBits)[d3dsd.Width*y+x] = 0x00000000;
}
else
{
// Handle 16-bit formats
if( ((WORD*)d3dlr.pBits)[d3dsd.Width*y+x] == dwColorKey )
((WORD*)d3dlr.pBits)[d3dsd.Width*y+x] = 0x0000;
}
}
}
// Unlock the texture and return OK.
pTexture->UnlockRect(0);
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: D3DUtil_CreateVertexShader()
// Desc: Assembles and creates a file-based vertex shader
//-----------------------------------------------------------------------------
HRESULT D3DUtil_CreateVertexShader( LPDIRECT3DDEVICE8 pd3dDevice,
TCHAR* strFilename, DWORD* pdwVertexDecl,
DWORD* pdwVertexShader )
{
LPD3DXBUFFER pCode;
TCHAR strPath[MAX_PATH];
HRESULT hr;
// Get the path to the vertex shader file
DXUtil_FindMediaFile( strPath, strFilename );
// Assemble the vertex shader file
if( FAILED( hr = D3DXAssembleShaderFromFile( strPath, 0, NULL, &pCode, NULL ) ) )
return hr;
// Create the vertex shader
hr = pd3dDevice->CreateVertexShader( pdwVertexDecl,
(DWORD*)pCode->GetBufferPointer(),
pdwVertexShader, 0 );
pCode->Release();
return hr;
}
//-----------------------------------------------------------------------------
// Name: D3DUtil_GetCubeMapViewMatrix()
// Desc: Returns a view matrix for rendering to a face of a cubemap.
//-----------------------------------------------------------------------------
D3DXMATRIX D3DUtil_GetCubeMapViewMatrix( DWORD dwFace )
{
D3DXVECTOR3 vEyePt = D3DXVECTOR3( 0.0f, 0.0f, 0.0f );
D3DXVECTOR3 vLookDir;
D3DXVECTOR3 vUpDir;
switch( dwFace )
{
case D3DCUBEMAP_FACE_POSITIVE_X:
vLookDir = D3DXVECTOR3( 1.0f, 0.0f, 0.0f );
vUpDir = D3DXVECTOR3( 0.0f, 1.0f, 0.0f );
break;
case D3DCUBEMAP_FACE_NEGATIVE_X:
vLookDir = D3DXVECTOR3(-1.0f, 0.0f, 0.0f );
vUpDir = D3DXVECTOR3( 0.0f, 1.0f, 0.0f );
break;
case D3DCUBEMAP_FACE_POSITIVE_Y:
vLookDir = D3DXVECTOR3( 0.0f, 1.0f, 0.0f );
vUpDir = D3DXVECTOR3( 0.0f, 0.0f,-1.0f );
break;
case D3DCUBEMAP_FACE_NEGATIVE_Y:
vLookDir = D3DXVECTOR3( 0.0f,-1.0f, 0.0f );
vUpDir = D3DXVECTOR3( 0.0f, 0.0f, 1.0f );
break;
case D3DCUBEMAP_FACE_POSITIVE_Z:
vLookDir = D3DXVECTOR3( 0.0f, 0.0f, 1.0f );
vUpDir = D3DXVECTOR3( 0.0f, 1.0f, 0.0f );
break;
case D3DCUBEMAP_FACE_NEGATIVE_Z:
vLookDir = D3DXVECTOR3( 0.0f, 0.0f,-1.0f );
vUpDir = D3DXVECTOR3( 0.0f, 1.0f, 0.0f );
break;
}
// Set the view transform for this cubemap surface
D3DXMATRIX matView;
D3DXMatrixLookAtLH( &matView, &vEyePt, &vLookDir, &vUpDir );
return matView;
}
//-----------------------------------------------------------------------------
// Name: D3DUtil_GetRotationFromCursor()
// Desc: Returns a quaternion for the rotation implied by the window's cursor
// position.
//-----------------------------------------------------------------------------
D3DXQUATERNION D3DUtil_GetRotationFromCursor( HWND hWnd,
FLOAT fTrackBallRadius )
{
POINT pt;
RECT rc;
GetCursorPos( &pt );
GetClientRect( hWnd, &rc );
ScreenToClient( hWnd, &pt );
FLOAT sx = ( ( ( 2.0f * pt.x ) / (rc.right-rc.left) ) - 1 );
FLOAT sy = ( ( ( 2.0f * pt.y ) / (rc.bottom-rc.top) ) - 1 );
FLOAT sz;
if( sx == 0.0f && sy == 0.0f )
return D3DXQUATERNION( 0.0f, 0.0f, 0.0f, 1.0f );
FLOAT d1 = 0.0f;
FLOAT d2 = sqrtf( sx*sx + sy*sy );
if( d2 < fTrackBallRadius * 0.70710678118654752440 ) // Inside sphere
sz = sqrtf( fTrackBallRadius*fTrackBallRadius - d2*d2 );
else // On hyperbola
sz = (fTrackBallRadius*fTrackBallRadius) / (2.0f*d2);
// Get two points on trackball's sphere
D3DXVECTOR3 p1( sx, sy, sz );
D3DXVECTOR3 p2( 0.0f, 0.0f, fTrackBallRadius );
// Get axis of rotation, which is cross product of p1 and p2
D3DXVECTOR3 vAxis;
D3DXVec3Cross( &vAxis, &p1, &p2);
// Calculate angle for the rotation about that axis
FLOAT t = D3DXVec3Length( &(p2-p1) ) / ( 2.0f*fTrackBallRadius );
if( t > +1.0f) t = +1.0f;
if( t < -1.0f) t = -1.0f;
FLOAT fAngle = 2.0f * asinf( t );
// Convert axis to quaternion
D3DXQUATERNION quat;
D3DXQuaternionRotationAxis( &quat, &vAxis, fAngle );
return quat;
}
//-----------------------------------------------------------------------------
// Name: D3DUtil_SetDeviceCursor
// Desc: Gives the D3D device a cursor with image and hotspot from hCursor.
//-----------------------------------------------------------------------------
HRESULT D3DUtil_SetDeviceCursor( LPDIRECT3DDEVICE8 pd3dDevice, HCURSOR hCursor,
BOOL bAddWatermark )
{
HRESULT hr = E_FAIL;
ICONINFO iconinfo;
BOOL bBWCursor;
LPDIRECT3DSURFACE8 pCursorBitmap = NULL;
HDC hdcColor = NULL;
HDC hdcMask = NULL;
HDC hdcScreen = NULL;
BITMAP bm;
DWORD dwWidth;
DWORD dwHeightSrc;
DWORD dwHeightDest;
COLORREF crColor;
COLORREF crMask;
UINT x;
UINT y;
BITMAPINFO bmi;
COLORREF* pcrArrayColor = NULL;
COLORREF* pcrArrayMask = NULL;
DWORD* pBitmap;
HGDIOBJ hgdiobjOld;
ZeroMemory( &iconinfo, sizeof(iconinfo) );
if( !GetIconInfo( hCursor, &iconinfo ) )
goto End;
if (0 == GetObject((HGDIOBJ)iconinfo.hbmMask, sizeof(BITMAP), (LPVOID)&bm))
goto End;
dwWidth = bm.bmWidth;
dwHeightSrc = bm.bmHeight;
if( iconinfo.hbmColor == NULL )
{
bBWCursor = TRUE;
dwHeightDest = dwHeightSrc / 2;
}
else
{
bBWCursor = FALSE;
dwHeightDest = dwHeightSrc;
}
// Create a surface for the fullscreen cursor
if( FAILED( hr = pd3dDevice->CreateImageSurface( dwWidth, dwHeightDest,
D3DFMT_A8R8G8B8, &pCursorBitmap ) ) )
{
goto End;
}
pcrArrayMask = new DWORD[dwWidth * dwHeightSrc];
ZeroMemory(&bmi, sizeof(bmi));
bmi.bmiHeader.biSize = sizeof(bmi.bmiHeader);
bmi.bmiHeader.biWidth = dwWidth;
bmi.bmiHeader.biHeight = dwHeightSrc;
bmi.bmiHeader.biPlanes = 1;
bmi.bmiHeader.biBitCount = 32;
bmi.bmiHeader.biCompression = BI_RGB;
hdcScreen = GetDC( NULL );
hdcMask = CreateCompatibleDC( hdcScreen );
if( hdcMask == NULL )
{
hr = E_FAIL;
goto End;
}
hgdiobjOld = SelectObject(hdcMask, iconinfo.hbmMask);
GetDIBits(hdcMask, iconinfo.hbmMask, 0, dwHeightSrc,
pcrArrayMask, &bmi, DIB_RGB_COLORS);
SelectObject(hdcMask, hgdiobjOld);
if (!bBWCursor)
{
pcrArrayColor = new DWORD[dwWidth * dwHeightDest];
hdcColor = CreateCompatibleDC( GetDC( NULL ) );
if( hdcColor == NULL )
{
hr = E_FAIL;
goto End;
}
SelectObject(hdcColor, iconinfo.hbmColor);
GetDIBits(hdcColor, iconinfo.hbmColor, 0, dwHeightDest,
pcrArrayColor, &bmi, DIB_RGB_COLORS);
}
// Transfer cursor image into the surface
D3DLOCKED_RECT lr;
pCursorBitmap->LockRect( &lr, NULL, 0 );
pBitmap = (DWORD*)lr.pBits;
for( y = 0; y < dwHeightDest; y++ )
{
for( x = 0; x < dwWidth; x++ )
{
if (bBWCursor)
{
crColor = pcrArrayMask[dwWidth*(dwHeightDest-1-y) + x];
crMask = pcrArrayMask[dwWidth*(dwHeightSrc-1-y) + x];
}
else
{
crColor = pcrArrayColor[dwWidth*(dwHeightDest-1-y) + x];
crMask = pcrArrayMask[dwWidth*(dwHeightDest-1-y) + x];
}
if (crMask == 0)
pBitmap[dwWidth*y + x] = 0xff000000 | crColor;
else
pBitmap[dwWidth*y + x] = 0x00000000;
// It may be helpful to make the D3D cursor look slightly
// different from the Windows cursor so you can distinguish
// between the two when developing/testing code. When
// bAddWatermark is TRUE, the following code adds some
// small grey "D3D" characters to the upper-left corner of
// the D3D cursor image.
if( bAddWatermark && x < 12 && y < 5 )
{
// 11.. 11.. 11.. .... CCC0
// 1.1. ..1. 1.1. .... A2A0
// 1.1. .1.. 1.1. .... A4A0
// 1.1. ..1. 1.1. .... A2A0
// 11.. 11.. 11.. .... CCC0
const WORD wMask[5] = { 0xccc0, 0xa2a0, 0xa4a0, 0xa2a0, 0xccc0 };
if( wMask[y] & (1 << (15 - x)) )
{
pBitmap[dwWidth*y + x] |= 0xff808080;
}
}
}
}
pCursorBitmap->UnlockRect();
// Set the device cursor
if( FAILED( hr = pd3dDevice->SetCursorProperties( iconinfo.xHotspot,
iconinfo.yHotspot, pCursorBitmap ) ) )
{
goto End;
}
hr = S_OK;
End:
if( iconinfo.hbmMask != NULL )
DeleteObject( iconinfo.hbmMask );
if( iconinfo.hbmColor != NULL )
DeleteObject( iconinfo.hbmColor );
if( hdcScreen != NULL )
ReleaseDC( NULL, hdcScreen );
if( hdcColor != NULL )
DeleteDC( hdcColor );
if( hdcMask != NULL )
DeleteDC( hdcMask );
SAFE_DELETE_ARRAY( pcrArrayColor );
SAFE_DELETE_ARRAY( pcrArrayMask );
SAFE_RELEASE( pCursorBitmap );
return hr;
}
//-----------------------------------------------------------------------------
// Name: D3DXQuaternionUnitAxisToUnitAxis2
// Desc: Axis to axis quaternion double angle (no normalization)
// Takes two points on unit sphere an angle THETA apart, returns
// quaternion that represents a rotation around cross product by 2*THETA.
//-----------------------------------------------------------------------------
inline D3DXQUATERNION* WINAPI D3DXQuaternionUnitAxisToUnitAxis2
( D3DXQUATERNION *pOut, const D3DXVECTOR3 *pvFrom, const D3DXVECTOR3 *pvTo)
{
D3DXVECTOR3 vAxis;
D3DXVec3Cross(&vAxis, pvFrom, pvTo); // proportional to sin(theta)
pOut->x = vAxis.x;
pOut->y = vAxis.y;
pOut->z = vAxis.z;
pOut->w = D3DXVec3Dot( pvFrom, pvTo );
return pOut;
}
//-----------------------------------------------------------------------------
// Name: D3DXQuaternionAxisToAxis
// Desc: Axis to axis quaternion
// Takes two points on unit sphere an angle THETA apart, returns
// quaternion that represents a rotation around cross product by theta.
//-----------------------------------------------------------------------------
inline D3DXQUATERNION* WINAPI D3DXQuaternionAxisToAxis
( D3DXQUATERNION *pOut, const D3DXVECTOR3 *pvFrom, const D3DXVECTOR3 *pvTo)
{
D3DXVECTOR3 vA, vB;
D3DXVec3Normalize(&vA, pvFrom);
D3DXVec3Normalize(&vB, pvTo);
D3DXVECTOR3 vHalf(vA + vB);
D3DXVec3Normalize(&vHalf, &vHalf);
return D3DXQuaternionUnitAxisToUnitAxis2(pOut, &vA, &vHalf);
}
//-----------------------------------------------------------------------------
// Name:
// Desc:
//-----------------------------------------------------------------------------
CD3DArcBall::CD3DArcBall()
{
D3DXQuaternionIdentity( &m_qDown );
D3DXQuaternionIdentity( &m_qNow );
D3DXMatrixIdentity( &m_matRotation );
D3DXMatrixIdentity( &m_matRotationDelta );
D3DXMatrixIdentity( &m_matTranslation );
D3DXMatrixIdentity( &m_matTranslationDelta );
m_bDrag = FALSE;
m_fRadiusTranslation = 1.0f;
m_bRightHanded = FALSE;
}
//-----------------------------------------------------------------------------
// Name:
// Desc:
//-----------------------------------------------------------------------------
VOID CD3DArcBall::SetWindow( int iWidth, int iHeight, float fRadius )
{
// Set ArcBall info
m_iWidth = iWidth;
m_iHeight = iHeight;
m_fRadius = fRadius;
}
//-----------------------------------------------------------------------------
// Name:
// Desc:
//-----------------------------------------------------------------------------
D3DXVECTOR3 CD3DArcBall::ScreenToVector( int sx, int sy )
{
// Scale to screen
FLOAT x = -(sx - m_iWidth/2) / (m_fRadius*m_iWidth/2);
FLOAT y = (sy - m_iHeight/2) / (m_fRadius*m_iHeight/2);
if( m_bRightHanded )
{
x = -x;
y = -y;
}
FLOAT z = 0.0f;
FLOAT mag = x*x + y*y;
if( mag > 1.0f )
{
FLOAT scale = 1.0f/sqrtf(mag);
x *= scale;
y *= scale;
}
else
z = sqrtf( 1.0f - mag );
// Return vector
return D3DXVECTOR3( x, y, z );
}
//-----------------------------------------------------------------------------
// Name:
// Desc:
//-----------------------------------------------------------------------------
VOID CD3DArcBall::SetRadius( FLOAT fRadius )
{
m_fRadiusTranslation = fRadius;
}
//-----------------------------------------------------------------------------
// Name:
// Desc:
//-----------------------------------------------------------------------------
LRESULT CD3DArcBall::HandleMouseMessages( HWND hWnd, UINT uMsg, WPARAM wParam,
LPARAM lParam )
{
static int iCurMouseX; // Saved mouse position
static int iCurMouseY;
static D3DXVECTOR3 s_vDown; // Button down vector
// Current mouse position
int iMouseX = LOWORD(lParam);
int iMouseY = HIWORD(lParam);
switch( uMsg )
{
case WM_RBUTTONDOWN:
case WM_MBUTTONDOWN:
// Store off the position of the cursor when the button is pressed
iCurMouseX = iMouseX;
iCurMouseY = iMouseY;
return TRUE;
case WM_LBUTTONDOWN:
// Start drag mode
m_bDrag = TRUE;
s_vDown = ScreenToVector( iMouseX, iMouseY );
m_qDown = m_qNow;
return TRUE;
case WM_LBUTTONUP:
// End drag mode
m_bDrag = FALSE;
return TRUE;
case WM_MOUSEMOVE:
// Drag object
if( MK_LBUTTON&wParam )
{
if( m_bDrag )
{
// recompute m_qNow
D3DXVECTOR3 vCur = ScreenToVector( iMouseX, iMouseY );
D3DXQUATERNION qAxisToAxis;
D3DXQuaternionAxisToAxis(&qAxisToAxis, &s_vDown, &vCur);
m_qNow = m_qDown;
m_qNow *= qAxisToAxis;
D3DXMatrixRotationQuaternion(&m_matRotationDelta, &qAxisToAxis);
}
else
D3DXMatrixIdentity(&m_matRotationDelta);
D3DXMatrixRotationQuaternion(&m_matRotation, &m_qNow);
m_bDrag = TRUE;
}
else if( (MK_RBUTTON&wParam) || (MK_MBUTTON&wParam) )
{
// Normalize based on size of window and bounding sphere radius
FLOAT fDeltaX = ( iCurMouseX-iMouseX ) * m_fRadiusTranslation / m_iWidth;
FLOAT fDeltaY = ( iCurMouseY-iMouseY ) * m_fRadiusTranslation / m_iHeight;
if( wParam & MK_RBUTTON )
{
D3DXMatrixTranslation( &m_matTranslationDelta, -2*fDeltaX, 2*fDeltaY, 0.0f );
D3DXMatrixMultiply( &m_matTranslation, &m_matTranslation, &m_matTranslationDelta );
}
else // wParam & MK_MBUTTON
{
D3DXMatrixTranslation( &m_matTranslationDelta, 0.0f, 0.0f, 5*fDeltaY );
D3DXMatrixMultiply( &m_matTranslation, &m_matTranslation, &m_matTranslationDelta );
}
// Store mouse coordinate
iCurMouseX = iMouseX;
iCurMouseY = iMouseY;
}
return TRUE;
}
return FALSE;
}
//-----------------------------------------------------------------------------
// Name:
// Desc:
//-----------------------------------------------------------------------------
CD3DCamera::CD3DCamera()
{
// Set attributes for the view matrix
SetViewParams( D3DXVECTOR3(0.0f,0.0f,0.0f), D3DXVECTOR3(0.0f,0.0f,1.0f),
D3DXVECTOR3(0.0f,1.0f,0.0f) );
// Set attributes for the projection matrix
SetProjParams( D3DX_PI/4, 1.0f, 1.0f, 1000.0f );
}
//-----------------------------------------------------------------------------
// Name:
// Desc:
//-----------------------------------------------------------------------------
VOID CD3DCamera::SetViewParams( D3DXVECTOR3 &vEyePt, D3DXVECTOR3& vLookatPt,
D3DXVECTOR3& vUpVec )
{
// Set attributes for the view matrix
m_vEyePt = vEyePt;
m_vLookatPt = vLookatPt;
m_vUpVec = vUpVec;
D3DXVec3Normalize( &m_vView, &(m_vLookatPt - m_vEyePt) );
D3DXVec3Cross( &m_vCross, &m_vView, &m_vUpVec );
D3DXMatrixLookAtLH( &m_matView, &m_vEyePt, &m_vLookatPt, &m_vUpVec );
D3DXMatrixInverse( &m_matBillboard, NULL, &m_matView );
m_matBillboard._41 = 0.0f;
m_matBillboard._42 = 0.0f;
m_matBillboard._43 = 0.0f;
}
//-----------------------------------------------------------------------------
// Name:
// Desc:
//-----------------------------------------------------------------------------
VOID CD3DCamera::SetProjParams( FLOAT fFOV, FLOAT fAspect, FLOAT fNearPlane,
FLOAT fFarPlane )
{
// Set attributes for the projection matrix
m_fFOV = fFOV;
m_fAspect = fAspect;
m_fNearPlane = fNearPlane;
m_fFarPlane = fFarPlane;
D3DXMatrixPerspectiveFovLH( &m_matProj, fFOV, fAspect, fNearPlane, fFarPlane );
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,341 @@
//-----------------------------------------------------------------------------
// File: DIUtil.cpp
//
// Desc: DirectInput framework class using semantic mapping. Feel free to use
// this class as a starting point for adding extra functionality.
//
// Copyright (C) 1995-2001 Microsoft Corporation. All Rights Reserved.
//-----------------------------------------------------------------------------
#define STRICT
#define DIRECTINPUT_VERSION 0x0800
#include <basetsd.h>
#include <tchar.h>
#include <stdio.h>
#include "DIUtil.h"
#include "DXUtil.h"
//-----------------------------------------------------------------------------
// Name: CInputDeviceManager()
// Desc: Constructor
//-----------------------------------------------------------------------------
CInputDeviceManager::CInputDeviceManager()
{
HRESULT hr = CoInitialize(NULL);
m_bCleanupCOM = SUCCEEDED(hr);
m_dwNumDevices = 0;
m_dwMaxDevices = 10;
m_pDI = NULL;
// Allocate DeviceInfo structs
m_pDevices = NULL;
m_pDevices = (DeviceInfo*) realloc( m_pDevices, m_dwMaxDevices*sizeof(DeviceInfo) );
ZeroMemory( m_pDevices, m_dwMaxDevices*sizeof(DeviceInfo) );
}
//-----------------------------------------------------------------------------
// Name: ~CInputDeviceManager()
// Desc: Destructor
//-----------------------------------------------------------------------------
CInputDeviceManager::~CInputDeviceManager()
{
if( m_pDevices )
{
// Release() all devices
for( DWORD i=0; i<m_dwNumDevices; i++ )
{
m_pDevices[i].pdidDevice->Unacquire();
m_pDevices[i].pdidDevice->Release();
m_pDevices[i].pdidDevice = NULL;
}
free( m_pDevices );
}
// Release() base object
SAFE_RELEASE( m_pDI );
if( m_bCleanupCOM )
CoUninitialize();
}
//-----------------------------------------------------------------------------
// Name: GetDevices()
// Desc: Get the DeviceInfo array and number of devices
//-----------------------------------------------------------------------------
HRESULT CInputDeviceManager::GetDevices( DeviceInfo** ppDeviceInfo,
DWORD* pdwCount )
{
if( NULL==ppDeviceInfo || NULL==pdwCount )
return E_INVALIDARG;
(*ppDeviceInfo) = m_pDevices;
(*pdwCount) = m_dwNumDevices;
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: AddDevice()
// Desc: Add the provided device to the list and perform initialization
//-----------------------------------------------------------------------------
HRESULT CInputDeviceManager::AddDevice( const DIDEVICEINSTANCE* pdidi,
const LPDIRECTINPUTDEVICE8 pdidDevice )
{
HRESULT hr;
DWORD dwDeviceType = pdidi->dwDevType;
pdidDevice->Unacquire();
// Set the device's coop level
hr = pdidDevice->SetCooperativeLevel( m_hWnd, DISCL_NONEXCLUSIVE|DISCL_FOREGROUND );
if( FAILED(hr) )
return hr;
// Add new DeviceInfo struct to list, and resize array if needed
m_dwNumDevices++;
if( m_dwNumDevices > m_dwMaxDevices )
{
m_dwMaxDevices += 10;
m_pDevices = (DeviceInfo*) realloc( m_pDevices, m_dwMaxDevices*sizeof(DeviceInfo) );
ZeroMemory( m_pDevices + m_dwMaxDevices - 10, 10*sizeof(DeviceInfo) );
}
DWORD dwCurrentDevice = m_dwNumDevices-1;
m_pDevices[dwCurrentDevice].pdidDevice = pdidDevice;
m_pDevices[dwCurrentDevice].pdidDevice->AddRef();
// Callback into the app so it can adjust the device and set
// the m_pDevices[dwCurrentDevice].pParam field with a device state struct
if( m_AddDeviceCallback )
{
hr = m_AddDeviceCallback( &m_pDevices[dwCurrentDevice], pdidi, m_AddDeviceCallbackParam );
if( FAILED(hr) )
return hr;
}
// Build the action map
hr = m_pDevices[dwCurrentDevice].pdidDevice->BuildActionMap( &m_diaf, m_strUserName, 0 );
if( FAILED(hr) )
return hr;
// Set the action map for the current device
hr = m_pDevices[dwCurrentDevice].pdidDevice->SetActionMap( &m_diaf, m_strUserName, 0 );
if( FAILED(hr) )
return hr;
// Continue enumerating suitable devices
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: EnumSuitableDevicesCB()
// Desc: Callback function for device enumeration. Adds all devices which
// met the search criteria
//-----------------------------------------------------------------------------
BOOL CALLBACK EnumSuitableDevicesCB( LPCDIDEVICEINSTANCE pdidi,
LPDIRECTINPUTDEVICE8 pdidDevice,
DWORD dwFlags, DWORD dwDeviceRemaining,
VOID* pContext )
{
// Add the device to the device manager's internal list
((CInputDeviceManager*)pContext)->AddDevice( pdidi, pdidDevice );
// Continue enumerating suitable devices
return DIENUM_CONTINUE;
}
//-----------------------------------------------------------------------------
// Name: SetActionFormat()
// Desc: Set the action format to the provided DIACTIONFORMAT structure, and
// destroy and recreate device list if flagged
//-----------------------------------------------------------------------------
HRESULT CInputDeviceManager::SetActionFormat( DIACTIONFORMAT& diaf, BOOL bReenumerate )
{
HRESULT hr = S_OK;
// Store the new action format
m_diaf = diaf;
// Only destroy and re-enumerate devices if the caller explicitly wants to. The
// device list may be used within a loop, and kicking off an enumeration while
// the device array is in use would cause problems.
if( bReenumerate )
{
// Cleanup any previously enumerated devices
for( DWORD i=0; i<m_dwNumDevices; i++ )
{
m_pDevices[i].pdidDevice->Unacquire();
m_pDevices[i].pdidDevice->Release();
m_pDevices[i].pdidDevice = NULL;
}
m_dwNumDevices = 0;
// Enumerate suitable DirectInput devices
hr = m_pDI->EnumDevicesBySemantics( m_strUserName, &m_diaf,
EnumSuitableDevicesCB, this, 0L );
if( FAILED(hr) )
return hr;
}
else // Just apply the new maps.
{
// Devices must be unacquired to have a new action map set.
UnacquireDevices();
// Apply the new action map to the current devices.
for( DWORD i=0; i<m_dwNumDevices; i++ )
{
hr = m_pDevices[i].pdidDevice->BuildActionMap( &m_diaf, m_strUserName, 0 );
if( FAILED(hr) )
return hr;
hr = m_pDevices[i].pdidDevice->SetActionMap( &m_diaf, m_strUserName, 0 );
if( FAILED(hr) )
return hr;
}
}
if( FAILED(hr) )
return hr;
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: Create()
// Desc: Create DirectInput object and perform initialization
//-----------------------------------------------------------------------------
HRESULT CInputDeviceManager::Create( HWND hWnd, TCHAR* strUserName,
DIACTIONFORMAT& diaf,
LPDIMANAGERCALLBACK AddDeviceCallback,
LPVOID pCallbackParam )
{
HRESULT hr;
// Store data
m_hWnd = hWnd;
m_strUserName = strUserName;
m_AddDeviceCallback = AddDeviceCallback;
m_AddDeviceCallbackParam = pCallbackParam;
// Create the base DirectInput object
hr = DirectInput8Create( GetModuleHandle(NULL), DIRECTINPUT_VERSION,
IID_IDirectInput8, (VOID**)&m_pDI, NULL );
if( FAILED(hr) )
return hr;
hr = SetActionFormat( diaf, TRUE );
if( FAILED(hr) )
return hr;
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: ConfigureDevices()
// Desc: Pause input and display the device configuration UI
//-----------------------------------------------------------------------------
HRESULT CInputDeviceManager::ConfigureDevices( HWND hWnd, IUnknown* pSurface,
VOID* ConfigureDevicesCB,
DWORD dwFlags, LPVOID pvCBParam )
{
HRESULT hr;
// Initialize all the colors here
DICOLORSET dics;
ZeroMemory(&dics, sizeof(DICOLORSET));
dics.dwSize = sizeof(DICOLORSET);
// Fill in all the params
DICONFIGUREDEVICESPARAMS dicdp;
ZeroMemory(&dicdp, sizeof(dicdp));
dicdp.dwSize = sizeof(dicdp);
dicdp.dwcFormats = 1;
dicdp.lprgFormats = &m_diaf;
dicdp.hwnd = hWnd;
dicdp.lpUnkDDSTarget = pSurface;
if( m_strUserName )
{
dicdp.dwcUsers = 1;
dicdp.lptszUserNames = m_strUserName;
}
// Unacquire the devices so that mouse doesn't control the game while in control panel
UnacquireDevices();
hr = m_pDI->ConfigureDevices( (LPDICONFIGUREDEVICESCALLBACK)ConfigureDevicesCB,
&dicdp, dwFlags, pvCBParam );
if( FAILED(hr) )
return hr;
if( dwFlags & DICD_EDIT )
{
// Re-set up the devices
hr = SetActionFormat( m_diaf, TRUE );
if( FAILED(hr) )
return hr;
}
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: UnacquireDevices()
// Desc: Unacquire all devices in the member list
//-----------------------------------------------------------------------------
VOID CInputDeviceManager::UnacquireDevices()
{
for( DWORD i=0; i<m_dwNumDevices; i++ )
m_pDevices[i].pdidDevice->Unacquire();
}
//-----------------------------------------------------------------------------
// Name: SetFocus()
// Desc: Sets the DirectInput focus to a new HWND
//-----------------------------------------------------------------------------
VOID CInputDeviceManager::SetFocus( HWND hWnd )
{
m_hWnd = hWnd;
UnacquireDevices();
for( DWORD i=0; i<m_dwNumDevices; i++ )
{
// Set the device's coop level
m_pDevices[i].pdidDevice->SetCooperativeLevel( m_hWnd,
DISCL_NONEXCLUSIVE|DISCL_FOREGROUND );
}
}

View File

@@ -0,0 +1,689 @@
//-----------------------------------------------------------------------------
// File: DMUtil.cpp
//
// Desc: DirectMusic framework classes for playing DirectMusic segments and
// DirectMusic scripts. Feel free to use this class as a starting point
// for adding extra functionality.
//
// Copyright (c) 1999-2001 Microsoft Corp. All rights reserved.
//-----------------------------------------------------------------------------
#define STRICT
#include <dmusicc.h>
#include <dmusici.h>
#include <dsound.h>
#include <dxerr8.h>
#include "DMUtil.h"
#include "DXUtil.h"
//-----------------------------------------------------------------------------
// Name: CMusicManager::CMusicManager()
// Desc: Constructs the class
//-----------------------------------------------------------------------------
CMusicManager::CMusicManager()
{
m_pLoader = NULL;
m_pPerformance = NULL;
// Initialize COM
HRESULT hr = CoInitialize(NULL);
m_bCleanupCOM = SUCCEEDED(hr);
}
//-----------------------------------------------------------------------------
// Name: CMusicManager::~CMusicManager()
// Desc: Destroys the class
//-----------------------------------------------------------------------------
CMusicManager::~CMusicManager()
{
SAFE_RELEASE( m_pLoader );
if( m_pPerformance )
{
// If there is any music playing, stop it.
m_pPerformance->Stop( NULL, NULL, 0, 0 );
m_pPerformance->CloseDown();
SAFE_RELEASE( m_pPerformance );
}
if( m_bCleanupCOM )
CoUninitialize();
}
//-----------------------------------------------------------------------------
// Name: CMusicManager::Initialize()
// Desc: Inits DirectMusic using a standard audio path
//-----------------------------------------------------------------------------
HRESULT CMusicManager::Initialize( HWND hWnd, DWORD dwPChannels, DWORD dwDefaultPathType )
{
HRESULT hr;
// Create loader object
if( FAILED( hr = CoCreateInstance( CLSID_DirectMusicLoader, NULL, CLSCTX_INPROC,
IID_IDirectMusicLoader8, (void**)&m_pLoader ) ) )
return DXTRACE_ERR( TEXT("CoCreateInstance"), hr );
// Create performance object
if( FAILED( hr = CoCreateInstance( CLSID_DirectMusicPerformance, NULL, CLSCTX_INPROC,
IID_IDirectMusicPerformance8, (void**)&m_pPerformance ) ) )
return DXTRACE_ERR( TEXT("CoCreateInstance"), hr );
// Initialize the performance with the standard audio path.
// This initializes both DirectMusic and DirectSound and
// sets up the synthesizer. Typcially its easist to use an
// audio path for playing music and sound effects.
if( FAILED( hr = m_pPerformance->InitAudio( NULL, NULL, hWnd, dwDefaultPathType,
dwPChannels, DMUS_AUDIOF_ALL, NULL ) ) )
{
if( hr == DSERR_NODRIVER )
{
DXTRACE( "Warning: No sound card found\n" );
return hr;
}
return DXTRACE_ERR( TEXT("InitAudio"), hr );
}
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: CMusicManager::SetSearchDirectory()
// Desc: Sets the search directory. If not called, the current working
// directory is used to load content.
//-----------------------------------------------------------------------------
HRESULT CMusicManager::SetSearchDirectory( const TCHAR* strMediaPath )
{
if( NULL == m_pLoader )
return E_UNEXPECTED;
// DMusic only takes wide strings
WCHAR wstrMediaPath[MAX_PATH];
DXUtil_ConvertGenericStringToWide( wstrMediaPath, strMediaPath );
return m_pLoader->SetSearchDirectory( GUID_DirectMusicAllTypes,
wstrMediaPath, FALSE );
}
//-----------------------------------------------------------------------------
// Name: CMusicManager::GetDefaultAudioPath()
// Desc:
//-----------------------------------------------------------------------------
IDirectMusicAudioPath8* CMusicManager::GetDefaultAudioPath()
{
IDirectMusicAudioPath8* pAudioPath = NULL;
if( NULL == m_pPerformance )
return NULL;
m_pPerformance->GetDefaultAudioPath( &pAudioPath );
return pAudioPath;
}
//-----------------------------------------------------------------------------
// Name: CMusicManager::CollectGarbage()
// Desc: Tells the loader to cleanup any garbage from previously
// released objects.
//-----------------------------------------------------------------------------
VOID CMusicManager::CollectGarbage()
{
if( m_pLoader )
m_pLoader->CollectGarbage();
}
//-----------------------------------------------------------------------------
// Name: CMusicManager::CreateSegmentFromFile()
// Desc:
//-----------------------------------------------------------------------------
HRESULT CMusicManager::CreateSegmentFromFile( CMusicSegment** ppSegment,
TCHAR* strFileName,
BOOL bDownloadNow,
BOOL bIsMidiFile )
{
HRESULT hr;
IDirectMusicSegment8* pSegment = NULL;
// DMusic only takes wide strings
WCHAR wstrFileName[MAX_PATH];
DXUtil_ConvertGenericStringToWide( wstrFileName, strFileName );
if ( FAILED( hr = m_pLoader->LoadObjectFromFile( CLSID_DirectMusicSegment,
IID_IDirectMusicSegment8,
wstrFileName,
(LPVOID*) &pSegment ) ) )
{
if( hr == DMUS_E_LOADER_FAILEDOPEN )
return hr;
return DXTRACE_ERR( TEXT("LoadObjectFromFile"), hr );
}
*ppSegment = new CMusicSegment( m_pPerformance, m_pLoader, pSegment );
if (!*ppSegment)
return E_OUTOFMEMORY;
if( bIsMidiFile )
{
if( FAILED( hr = pSegment->SetParam( GUID_StandardMIDIFile,
0xFFFFFFFF, 0, 0, NULL ) ) )
return DXTRACE_ERR( TEXT("SetParam"), hr );
}
if( bDownloadNow )
{
if( FAILED( hr = (*ppSegment)->Download() ) )
return DXTRACE_ERR( TEXT("Download"), hr );
}
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: CMusicManager::CreateSegmentFromResource()
// Desc:
//-----------------------------------------------------------------------------
HRESULT CMusicManager::CreateSegmentFromResource( CMusicSegment** ppSegment,
TCHAR* strResource,
TCHAR* strResourceType,
BOOL bDownloadNow,
BOOL bIsMidiFile )
{
HRESULT hr;
IDirectMusicSegment8* pSegment = NULL;
HRSRC hres = NULL;
void* pMem = NULL;
DWORD dwSize = 0;
DMUS_OBJECTDESC objdesc;
// Find the resource
hres = FindResource( NULL,strResource,strResourceType );
if( NULL == hres )
return E_FAIL;
// Load the resource
pMem = (void*)LoadResource( NULL, hres );
if( NULL == pMem )
return E_FAIL;
// Store the size of the resource
dwSize = SizeofResource( NULL, hres );
// Set up our object description
ZeroMemory(&objdesc,sizeof(DMUS_OBJECTDESC));
objdesc.dwSize = sizeof(DMUS_OBJECTDESC);
objdesc.dwValidData = DMUS_OBJ_MEMORY | DMUS_OBJ_CLASS;
objdesc.guidClass = CLSID_DirectMusicSegment;
objdesc.llMemLength =(LONGLONG)dwSize;
objdesc.pbMemData = (BYTE*)pMem;
if (FAILED ( hr = m_pLoader->GetObject( &objdesc,
IID_IDirectMusicSegment8,
(void**)&pSegment ) ) )
{
if( hr == DMUS_E_LOADER_FAILEDOPEN )
return hr;
return DXTRACE_ERR( TEXT("LoadObjectFromFile"), hr );
}
*ppSegment = new CMusicSegment( m_pPerformance, m_pLoader, pSegment );
if( NULL == *ppSegment )
return E_OUTOFMEMORY;
if( bIsMidiFile )
{
// Do this to make sure that the default General MIDI set
// is connected appropriately to the MIDI file and
// all instruments sound correct.
if( FAILED( hr = pSegment->SetParam( GUID_StandardMIDIFile,
0xFFFFFFFF, 0, 0, NULL ) ) )
return DXTRACE_ERR( TEXT("SetParam"), hr );
}
if( bDownloadNow )
{
// The segment needs to be download first before playing.
// However, some apps may want to wait before calling this
// to because the download allocates memory for the
// instruments. The more instruments currently downloaded,
// the more memory is in use by the synthesizer.
if( FAILED( hr = (*ppSegment)->Download() ) )
return DXTRACE_ERR( TEXT("Download"), hr );
}
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: CMusicManager::CreateScriptFromFile()
// Desc:
//-----------------------------------------------------------------------------
HRESULT CMusicManager::CreateScriptFromFile( CMusicScript** ppScript,
TCHAR* strFileName )
{
HRESULT hr;
IDirectMusicScript* pScript = NULL;
// DMusic only takes wide strings
WCHAR wstrFileName[MAX_PATH];
DXUtil_ConvertGenericStringToWide( wstrFileName, strFileName );
if ( FAILED( hr = m_pLoader->LoadObjectFromFile( CLSID_DirectMusicScript,
IID_IDirectMusicScript8,
wstrFileName,
(LPVOID*) &pScript ) ) )
return DXTRACE_ERR_NOMSGBOX( TEXT("LoadObjectFromFile"), hr );
if ( FAILED( hr = pScript->Init( m_pPerformance, NULL ) ) )
return DXTRACE_ERR( TEXT("Init"), hr );
*ppScript = new CMusicScript( m_pPerformance, m_pLoader, pScript );
if (!*ppScript)
return E_OUTOFMEMORY;
return hr;
}
//-----------------------------------------------------------------------------
// Name: CMusicManager::CreateChordMapFromFile()
// Desc:
//-----------------------------------------------------------------------------
HRESULT CMusicManager::CreateChordMapFromFile( IDirectMusicChordMap8** ppChordMap,
TCHAR* strFileName )
{
// DMusic only takes wide strings
WCHAR wstrFileName[MAX_PATH];
DXUtil_ConvertGenericStringToWide( wstrFileName, strFileName );
return m_pLoader->LoadObjectFromFile( CLSID_DirectMusicChordMap,
IID_IDirectMusicChordMap8,
wstrFileName, (LPVOID*) ppChordMap );
}
//-----------------------------------------------------------------------------
// Name: CMusicManager::CreateChordMapFromFile()
// Desc:
//-----------------------------------------------------------------------------
HRESULT CMusicManager::CreateStyleFromFile( IDirectMusicStyle8** ppStyle,
TCHAR* strFileName )
{
// DMusic only takes wide strings
WCHAR wstrFileName[MAX_PATH];
DXUtil_ConvertGenericStringToWide( wstrFileName, strFileName );
return m_pLoader->LoadObjectFromFile( CLSID_DirectMusicStyle,
IID_IDirectMusicStyle8,
wstrFileName, (LPVOID*) ppStyle );
}
//-----------------------------------------------------------------------------
// Name: CMusicManager::GetMotifFromStyle()
// Desc:
//-----------------------------------------------------------------------------
HRESULT CMusicManager::GetMotifFromStyle( IDirectMusicSegment8** ppMotif8,
TCHAR* strStyle, TCHAR* strMotif )
{
HRESULT hr;
IDirectMusicStyle8* pStyle = NULL;
IDirectMusicSegment* pMotif = NULL;
if( FAILED( hr = CreateStyleFromFile( &pStyle, strStyle ) ) )
return DXTRACE_ERR( TEXT("CreateStyleFromFile"), hr );
if( pStyle )
{
// DMusic only takes wide strings
WCHAR wstrMotif[MAX_PATH];
DXUtil_ConvertGenericStringToWide( wstrMotif, strMotif );
hr = pStyle->GetMotif( wstrMotif, &pMotif );
SAFE_RELEASE( pStyle );
if( FAILED( hr ) )
return DXTRACE_ERR( TEXT("GetMotif"), hr );
pMotif->QueryInterface( IID_IDirectMusicSegment8, (LPVOID*) ppMotif8 );
}
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: CMusicSegment::CMusicSegment()
// Desc: Constructs the class
//-----------------------------------------------------------------------------
CMusicSegment::CMusicSegment( IDirectMusicPerformance8* pPerformance,
IDirectMusicLoader8* pLoader,
IDirectMusicSegment8* pSegment )
{
m_pPerformance = pPerformance;
m_pLoader = pLoader;
m_pSegment = pSegment;
m_pEmbeddedAudioPath = NULL;
m_bDownloaded = FALSE;
// Try to pull out an audio path from the segment itself if there is one.
// This embedded audio path will be used instead of the default
// audio path if the app doesn't wish to use an overriding audio path.
IUnknown* pConfig = NULL;
if( SUCCEEDED( m_pSegment->GetAudioPathConfig( &pConfig ) ) )
{
m_pPerformance->CreateAudioPath( pConfig, TRUE, &m_pEmbeddedAudioPath );
SAFE_RELEASE( pConfig );
}
}
//-----------------------------------------------------------------------------
// Name: CMusicSegment::~CMusicSegment()
// Desc: Destroys the class
//-----------------------------------------------------------------------------
CMusicSegment::~CMusicSegment()
{
if( m_pSegment )
{
// Tell the loader that this object should now be released
if( m_pLoader )
m_pLoader->ReleaseObjectByUnknown( m_pSegment );
if( m_bDownloaded )
{
if( m_pEmbeddedAudioPath )
m_pSegment->Unload( m_pEmbeddedAudioPath );
else
m_pSegment->Unload( m_pPerformance );
}
SAFE_RELEASE( m_pEmbeddedAudioPath );
SAFE_RELEASE( m_pSegment );
}
m_pPerformance = NULL;
}
//-----------------------------------------------------------------------------
// Name: CMusicSegment::Play()
// Desc: Plays the sound using voice management flags. Pass in DSBPLAY_LOOPING
// in the dwFlags to loop the sound
//-----------------------------------------------------------------------------
HRESULT CMusicSegment::Play( DWORD dwFlags, IDirectMusicAudioPath8* pAudioPath )
{
if( m_pSegment == NULL || m_pPerformance == NULL )
return CO_E_NOTINITIALIZED;
if( !m_bDownloaded )
return E_FAIL;
// If an audio path was passed in then use it, otherwise
// use the embedded audio path if there was one.
if( pAudioPath == NULL && m_pEmbeddedAudioPath != NULL )
pAudioPath = m_pEmbeddedAudioPath;
// If pAudioPath is NULL then this plays on the default audio path.
return m_pPerformance->PlaySegmentEx( m_pSegment, 0, NULL, dwFlags,
0, 0, NULL, pAudioPath );
}
//-----------------------------------------------------------------------------
// Name: CMusicSegment::Download()
// Desc:
//-----------------------------------------------------------------------------
HRESULT CMusicSegment::Download( IDirectMusicAudioPath8* pAudioPath )
{
HRESULT hr;
if( m_pSegment == NULL )
return CO_E_NOTINITIALIZED;
// If no audio path was passed in, then download
// to the embedded audio path if it exists
// else download to the performance
if( pAudioPath == NULL )
{
if( m_pEmbeddedAudioPath )
hr = m_pSegment->Download( m_pEmbeddedAudioPath );
else
hr = m_pSegment->Download( m_pPerformance );
}
else
{
hr = m_pSegment->Download( pAudioPath );
}
if ( SUCCEEDED( hr ) )
m_bDownloaded = TRUE;
return hr;
}
//-----------------------------------------------------------------------------
// Name: CMusicSegment::Unload()
// Desc:
//-----------------------------------------------------------------------------
HRESULT CMusicSegment::Unload( IDirectMusicAudioPath8* pAudioPath )
{
HRESULT hr;
if( m_pSegment == NULL )
return CO_E_NOTINITIALIZED;
// If no audio path was passed in, then unload
// from the embedded audio path if it exists
// else unload from the performance
if( pAudioPath == NULL )
{
if( m_pEmbeddedAudioPath )
hr = m_pSegment->Unload( m_pEmbeddedAudioPath );
else
hr = m_pSegment->Unload( m_pPerformance );
}
else
{
hr = m_pSegment->Unload( pAudioPath );
}
if ( SUCCEEDED( hr ) )
m_bDownloaded = FALSE;
return hr;
}
//-----------------------------------------------------------------------------
// Name: CMusicSegment::IsPlaying()
// Desc:
//-----------------------------------------------------------------------------
BOOL CMusicSegment::IsPlaying()
{
if( m_pSegment == NULL || m_pPerformance == NULL )
return CO_E_NOTINITIALIZED;
return ( m_pPerformance->IsPlaying( m_pSegment, NULL ) == S_OK );
}
//-----------------------------------------------------------------------------
// Name: CMusicSegment::Stop()
// Desc: Stops the sound from playing
//-----------------------------------------------------------------------------
HRESULT CMusicSegment::Stop( DWORD dwFlags )
{
if( m_pSegment == NULL || m_pPerformance == NULL )
return CO_E_NOTINITIALIZED;
return m_pPerformance->Stop( m_pSegment, NULL, 0, dwFlags );;
}
//-----------------------------------------------------------------------------
// Name: CMusicSegment::SetRepeats()
// Desc:
//-----------------------------------------------------------------------------
HRESULT CMusicSegment::SetRepeats( DWORD dwRepeats )
{
if( m_pSegment == NULL )
return CO_E_NOTINITIALIZED;
return m_pSegment->SetRepeats( dwRepeats );
}
//-----------------------------------------------------------------------------
// Name: CMusicSegment::GetStyle()
// Desc:
//-----------------------------------------------------------------------------
HRESULT CMusicSegment::GetStyle( IDirectMusicStyle8** ppStyle, DWORD dwStyleIndex )
{
// Get the Style from the Segment by calling the Segment's GetData() with
// the data type GUID_StyleTrackStyle. 0xffffffff indicates to look at
// tracks in all TrackGroups in the segment. The first 0 indicates to
// retrieve the Style from the first Track in the indicated TrackGroup.
// The second 0 indicates to retrieve the Style from the beginning of the
// segment, i.e. time 0 in Segment time. If this Segment was loaded from a
// section file, there is only one Style and it is at time 0.
return m_pSegment->GetParam( GUID_IDirectMusicStyle, 0xffffffff, dwStyleIndex,
0, NULL, (VOID*)ppStyle );
}
//-----------------------------------------------------------------------------
// Name: CMusicScript::CMusicScript()
// Desc: Constructs the class
//-----------------------------------------------------------------------------
CMusicScript::CMusicScript( IDirectMusicPerformance8* pPerformance,
IDirectMusicLoader8* pLoader,
IDirectMusicScript8* pScript )
{
m_pPerformance = pPerformance;
m_pLoader = pLoader;
m_pScript = pScript;
}
//-----------------------------------------------------------------------------
// Name: CMusicScript::~CMusicScript()
// Desc: Destroys the class
//-----------------------------------------------------------------------------
CMusicScript::~CMusicScript()
{
if( m_pLoader )
{
// Tell the loader that this object should now be released
m_pLoader->ReleaseObjectByUnknown( m_pScript );
m_pLoader = NULL;
}
SAFE_RELEASE( m_pScript );
m_pPerformance = NULL;
}
//-----------------------------------------------------------------------------
// Name: CMusicScript::Play()
// Desc: Calls a routine in the script
//-----------------------------------------------------------------------------
HRESULT CMusicScript::CallRoutine( TCHAR* strRoutine )
{
// DMusic only takes wide strings
WCHAR wstrRoutine[MAX_PATH];
DXUtil_ConvertGenericStringToWide( wstrRoutine, strRoutine );
return m_pScript->CallRoutine( wstrRoutine, NULL );
}
//-----------------------------------------------------------------------------
// Name: CMusicScript::SetVariableNumber()
// Desc: Sets the value of a variable in the script
//-----------------------------------------------------------------------------
HRESULT CMusicScript::SetVariableNumber( TCHAR* strVariable, LONG lValue )
{
// DMusic only takes wide strings
WCHAR wstrVariable[MAX_PATH];
DXUtil_ConvertGenericStringToWide( wstrVariable, strVariable );
return m_pScript->SetVariableNumber( wstrVariable, lValue, NULL );
}
//-----------------------------------------------------------------------------
// Name: CMusicScript::GetVariableNumber()
// Desc: Gets the value of a variable in the script
//-----------------------------------------------------------------------------
HRESULT CMusicScript::GetVariableNumber( TCHAR* strVariable, LONG* plValue )
{
// DMusic only takes wide strings
WCHAR wstrVariable[MAX_PATH];
DXUtil_ConvertGenericStringToWide( wstrVariable, strVariable );
return m_pScript->GetVariableNumber( wstrVariable, plValue, NULL );
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,719 @@
//-----------------------------------------------------------------------------
// File: DXUtil.cpp
//
// Desc: Shortcut macros and functions for using DX objects
//
//
// Copyright (c) 1997-2001 Microsoft Corporation. All rights reserved
//-----------------------------------------------------------------------------
#define STRICT
#include <windows.h>
#include <mmsystem.h>
#include <tchar.h>
#include <stdio.h>
#include <stdarg.h>
#include "DXUtil.h"
//-----------------------------------------------------------------------------
// Name: DXUtil_GetDXSDKMediaPath()
// Desc: Returns the DirectX SDK media path
//-----------------------------------------------------------------------------
const TCHAR* DXUtil_GetDXSDKMediaPath()
{
static TCHAR strNull[2] = _T("");
static TCHAR strPath[MAX_PATH];
DWORD dwType;
DWORD dwSize = MAX_PATH;
HKEY hKey;
// Open the appropriate registry key
LONG lResult = RegOpenKeyEx( HKEY_LOCAL_MACHINE,
_T("Software\\Microsoft\\DirectX SDK"),
0, KEY_READ, &hKey );
if( ERROR_SUCCESS != lResult )
return strNull;
lResult = RegQueryValueEx( hKey, _T("DX81SDK Samples Path"), NULL,
&dwType, (BYTE*)strPath, &dwSize );
RegCloseKey( hKey );
if( ERROR_SUCCESS != lResult )
return strNull;
_tcscat( strPath, _T("\\Media\\") );
return strPath;
}
//-----------------------------------------------------------------------------
// Name: DXUtil_FindMediaFile()
// Desc: Returns a valid path to a DXSDK media file
//-----------------------------------------------------------------------------
HRESULT DXUtil_FindMediaFile( TCHAR* strPath, TCHAR* strFilename )
{
HANDLE file;
TCHAR strFullPath[1024];
TCHAR *strShortName;
DWORD cchPath;
if( NULL==strFilename || NULL==strPath )
return E_INVALIDARG;
// Build full path name from strFileName (strShortName will be just the leaf filename)
cchPath = GetFullPathName(strFilename, sizeof(strFullPath)/sizeof(TCHAR), strFullPath, &strShortName);
if ((cchPath == 0) || (sizeof(strFullPath)/sizeof(TCHAR) <= cchPath))
return E_FAIL;
// first try to find the filename given a full path
file = CreateFile( strFullPath, GENERIC_READ, FILE_SHARE_READ, NULL,
OPEN_EXISTING, 0, NULL );
if( INVALID_HANDLE_VALUE != file )
{
_tcscpy( strPath, strFullPath );
CloseHandle( file );
return S_OK;
}
// next try to find the filename in the current working directory (path stripped)
file = CreateFile( strShortName, GENERIC_READ, FILE_SHARE_READ, NULL,
OPEN_EXISTING, 0, NULL );
if( INVALID_HANDLE_VALUE != file )
{
_tcscpy( strPath, strShortName );
CloseHandle( file );
return S_OK;
}
// last, check if the file exists in the media directory
_stprintf( strPath, _T("%s%s"), DXUtil_GetDXSDKMediaPath(), strShortName );
file = CreateFile( strPath, GENERIC_READ, FILE_SHARE_READ, NULL,
OPEN_EXISTING, 0, NULL );
if( INVALID_HANDLE_VALUE != file )
{
CloseHandle( file );
return S_OK;
}
// On failure, just return the file as the path
_tcscpy( strPath, strFilename );
return E_FAIL;
}
//-----------------------------------------------------------------------------
// Name: DXUtil_ReadStringRegKey()
// Desc: Helper function to read a registry key string
//-----------------------------------------------------------------------------
HRESULT DXUtil_ReadStringRegKey( HKEY hKey, TCHAR* strRegName, TCHAR* strValue,
DWORD dwLength, TCHAR* strDefault )
{
DWORD dwType;
if( ERROR_SUCCESS != RegQueryValueEx( hKey, strRegName, 0, &dwType,
(BYTE*)strValue, &dwLength ) )
{
_tcscpy( strValue, strDefault );
}
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: DXUtil_WriteStringRegKey()
// Desc: Helper function to write a registry key string
//-----------------------------------------------------------------------------
HRESULT DXUtil_WriteStringRegKey( HKEY hKey, TCHAR* strRegName,
TCHAR* strValue )
{
if( ERROR_SUCCESS != RegSetValueEx( hKey, strRegName, 0, REG_SZ,
(BYTE*)strValue,
(_tcslen(strValue)+1)*sizeof(TCHAR) ) )
return E_FAIL;
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: DXUtil_ReadIntRegKey()
// Desc: Helper function to read a registry key int
//-----------------------------------------------------------------------------
HRESULT DXUtil_ReadIntRegKey( HKEY hKey, TCHAR* strRegName, DWORD* pdwValue,
DWORD dwDefault )
{
DWORD dwType;
DWORD dwLength = sizeof(DWORD);
if( ERROR_SUCCESS != RegQueryValueEx( hKey, strRegName, 0, &dwType,
(BYTE*)pdwValue, &dwLength ) )
{
*pdwValue = dwDefault;
}
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: DXUtil_WriteIntRegKey()
// Desc: Helper function to write a registry key int
//-----------------------------------------------------------------------------
HRESULT DXUtil_WriteIntRegKey( HKEY hKey, TCHAR* strRegName, DWORD dwValue )
{
if( ERROR_SUCCESS != RegSetValueEx( hKey, strRegName, 0, REG_DWORD,
(BYTE*)&dwValue, sizeof(DWORD) ) )
return E_FAIL;
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: DXUtil_ReadBoolRegKey()
// Desc: Helper function to read a registry key BOOL
//-----------------------------------------------------------------------------
HRESULT DXUtil_ReadBoolRegKey( HKEY hKey, TCHAR* strRegName, BOOL* pbValue,
BOOL bDefault )
{
DWORD dwType;
DWORD dwLength = sizeof(BOOL);
if( ERROR_SUCCESS != RegQueryValueEx( hKey, strRegName, 0, &dwType,
(BYTE*)pbValue, &dwLength ) )
{
*pbValue = bDefault;
}
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: DXUtil_WriteBoolRegKey()
// Desc: Helper function to write a registry key BOOL
//-----------------------------------------------------------------------------
HRESULT DXUtil_WriteBoolRegKey( HKEY hKey, TCHAR* strRegName, BOOL bValue )
{
if( ERROR_SUCCESS != RegSetValueEx( hKey, strRegName, 0, REG_DWORD,
(BYTE*)&bValue, sizeof(BOOL) ) )
return E_FAIL;
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: DXUtil_ReadGuidRegKey()
// Desc: Helper function to read a registry key guid
//-----------------------------------------------------------------------------
HRESULT DXUtil_ReadGuidRegKey( HKEY hKey, TCHAR* strRegName, GUID* pGuidValue,
GUID& guidDefault )
{
DWORD dwType;
DWORD dwLength = sizeof(GUID);
if( ERROR_SUCCESS != RegQueryValueEx( hKey, strRegName, 0, &dwType,
(LPBYTE) pGuidValue, &dwLength ) )
{
*pGuidValue = guidDefault;
}
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: DXUtil_WriteGuidRegKey()
// Desc: Helper function to write a registry key guid
//-----------------------------------------------------------------------------
HRESULT DXUtil_WriteGuidRegKey( HKEY hKey, TCHAR* strRegName, GUID guidValue )
{
if( ERROR_SUCCESS != RegSetValueEx( hKey, strRegName, 0, REG_BINARY,
(BYTE*)&guidValue, sizeof(GUID) ) )
return E_FAIL;
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: DXUtil_Timer()
// Desc: Performs timer opertations. Use the following commands:
// TIMER_RESET - to reset the timer
// TIMER_START - to start the timer
// TIMER_STOP - to stop (or pause) the timer
// TIMER_ADVANCE - to advance the timer by 0.1 seconds
// TIMER_GETABSOLUTETIME - to get the absolute system time
// TIMER_GETAPPTIME - to get the current time
// TIMER_GETELAPSEDTIME - to get the time that elapsed between
// TIMER_GETELAPSEDTIME calls
//-----------------------------------------------------------------------------
FLOAT __stdcall DXUtil_Timer( TIMER_COMMAND command )
{
static BOOL m_bTimerInitialized = FALSE;
static BOOL m_bUsingQPF = FALSE;
static BOOL m_bTimerStopped = TRUE;
static LONGLONG m_llQPFTicksPerSec = 0;
// Initialize the timer
if( FALSE == m_bTimerInitialized )
{
m_bTimerInitialized = TRUE;
// Use QueryPerformanceFrequency() to get frequency of timer. If QPF is
// not supported, we will timeGetTime() which returns milliseconds.
LARGE_INTEGER qwTicksPerSec;
m_bUsingQPF = QueryPerformanceFrequency( &qwTicksPerSec );
if( m_bUsingQPF )
m_llQPFTicksPerSec = qwTicksPerSec.QuadPart;
}
if( m_bUsingQPF )
{
static LONGLONG m_llStopTime = 0;
static LONGLONG m_llLastElapsedTime = 0;
static LONGLONG m_llBaseTime = 0;
double fTime;
double fElapsedTime;
LARGE_INTEGER qwTime;
// Get either the current time or the stop time, depending
// on whether we're stopped and what command was sent
if( m_llStopTime != 0 && command != TIMER_START && command != TIMER_GETABSOLUTETIME)
qwTime.QuadPart = m_llStopTime;
else
QueryPerformanceCounter( &qwTime );
// Return the elapsed time
if( command == TIMER_GETELAPSEDTIME )
{
fElapsedTime = (double) ( qwTime.QuadPart - m_llLastElapsedTime ) / (double) m_llQPFTicksPerSec;
m_llLastElapsedTime = qwTime.QuadPart;
return (FLOAT) fElapsedTime;
}
// Return the current time
if( command == TIMER_GETAPPTIME )
{
double fAppTime = (double) ( qwTime.QuadPart - m_llBaseTime ) / (double) m_llQPFTicksPerSec;
return (FLOAT) fAppTime;
}
// Reset the timer
if( command == TIMER_RESET )
{
m_llBaseTime = qwTime.QuadPart;
m_llLastElapsedTime = qwTime.QuadPart;
m_llStopTime = 0;
m_bTimerStopped = FALSE;
return 0.0f;
}
// Start the timer
if( command == TIMER_START )
{
if( m_bTimerStopped )
m_llBaseTime += qwTime.QuadPart - m_llStopTime;
m_llStopTime = 0;
m_llLastElapsedTime = qwTime.QuadPart;
m_bTimerStopped = FALSE;
return 0.0f;
}
// Stop the timer
if( command == TIMER_STOP )
{
m_llStopTime = qwTime.QuadPart;
m_llLastElapsedTime = qwTime.QuadPart;
m_bTimerStopped = TRUE;
return 0.0f;
}
// Advance the timer by 1/10th second
if( command == TIMER_ADVANCE )
{
m_llStopTime += m_llQPFTicksPerSec/10;
return 0.0f;
}
if( command == TIMER_GETABSOLUTETIME )
{
fTime = qwTime.QuadPart / (double) m_llQPFTicksPerSec;
return (FLOAT) fTime;
}
return -1.0f; // Invalid command specified
}
else
{
// Get the time using timeGetTime()
static double m_fLastElapsedTime = 0.0;
static double m_fBaseTime = 0.0;
static double m_fStopTime = 0.0;
double fTime;
double fElapsedTime;
// Get either the current time or the stop time, depending
// on whether we're stopped and what command was sent
if( m_fStopTime != 0.0 && command != TIMER_START && command != TIMER_GETABSOLUTETIME)
fTime = m_fStopTime;
else
fTime = timeGetTime() * 0.001;
// Return the elapsed time
if( command == TIMER_GETELAPSEDTIME )
{
fElapsedTime = (double) (fTime - m_fLastElapsedTime);
m_fLastElapsedTime = fTime;
return (FLOAT) fElapsedTime;
}
// Return the current time
if( command == TIMER_GETAPPTIME )
{
return (FLOAT) (fTime - m_fBaseTime);
}
// Reset the timer
if( command == TIMER_RESET )
{
m_fBaseTime = fTime;
m_fLastElapsedTime = fTime;
m_fStopTime = 0;
m_bTimerStopped = FALSE;
return 0.0f;
}
// Start the timer
if( command == TIMER_START )
{
if( m_bTimerStopped )
m_fBaseTime += fTime - m_fStopTime;
m_fStopTime = 0.0f;
m_fLastElapsedTime = fTime;
m_bTimerStopped = FALSE;
return 0.0f;
}
// Stop the timer
if( command == TIMER_STOP )
{
m_fStopTime = fTime;
m_fLastElapsedTime = fTime;
m_bTimerStopped = TRUE;
return 0.0f;
}
// Advance the timer by 1/10th second
if( command == TIMER_ADVANCE )
{
m_fStopTime += 0.1f;
return 0.0f;
}
if( command == TIMER_GETABSOLUTETIME )
{
return (FLOAT) fTime;
}
return -1.0f; // Invalid command specified
}
}
//-----------------------------------------------------------------------------
// Name: DXUtil_ConvertAnsiStringToWide()
// Desc: This is a UNICODE conversion utility to convert a CHAR string into a
// WCHAR string. cchDestChar defaults -1 which means it
// assumes strDest is large enough to store strSource
//-----------------------------------------------------------------------------
VOID DXUtil_ConvertAnsiStringToWide( WCHAR* wstrDestination, const CHAR* strSource,
int cchDestChar )
{
if( wstrDestination==NULL || strSource==NULL )
return;
if( cchDestChar == -1 )
cchDestChar = strlen(strSource)+1;
MultiByteToWideChar( CP_ACP, 0, strSource, -1,
wstrDestination, cchDestChar-1 );
wstrDestination[cchDestChar-1] = 0;
}
//-----------------------------------------------------------------------------
// Name: DXUtil_ConvertWideStringToAnsi()
// Desc: This is a UNICODE conversion utility to convert a WCHAR string into a
// CHAR string. cchDestChar defaults -1 which means it
// assumes strDest is large enough to store strSource
//-----------------------------------------------------------------------------
VOID DXUtil_ConvertWideStringToAnsi( CHAR* strDestination, const WCHAR* wstrSource,
int cchDestChar )
{
if( strDestination==NULL || wstrSource==NULL )
return;
if( cchDestChar == -1 )
cchDestChar = wcslen(wstrSource)+1;
WideCharToMultiByte( CP_ACP, 0, wstrSource, -1, strDestination,
cchDestChar-1, NULL, NULL );
strDestination[cchDestChar-1] = 0;
}
//-----------------------------------------------------------------------------
// Name: DXUtil_ConvertGenericStringToAnsi()
// Desc: This is a UNICODE conversion utility to convert a TCHAR string into a
// CHAR string. cchDestChar defaults -1 which means it
// assumes strDest is large enough to store strSource
//-----------------------------------------------------------------------------
VOID DXUtil_ConvertGenericStringToAnsi( CHAR* strDestination, const TCHAR* tstrSource,
int cchDestChar )
{
if( strDestination==NULL || tstrSource==NULL || cchDestChar == 0 )
return;
#ifdef _UNICODE
DXUtil_ConvertWideStringToAnsi( strDestination, tstrSource, cchDestChar );
#else
if( cchDestChar == -1 )
{
strcpy( strDestination, tstrSource );
}
else
{
strncpy( strDestination, tstrSource, cchDestChar );
strDestination[cchDestChar-1] = '\0';
}
#endif
}
//-----------------------------------------------------------------------------
// Name: DXUtil_ConvertGenericStringToWide()
// Desc: This is a UNICODE conversion utility to convert a TCHAR string into a
// WCHAR string. cchDestChar defaults -1 which means it
// assumes strDest is large enough to store strSource
//-----------------------------------------------------------------------------
VOID DXUtil_ConvertGenericStringToWide( WCHAR* wstrDestination, const TCHAR* tstrSource,
int cchDestChar )
{
if( wstrDestination==NULL || tstrSource==NULL || cchDestChar == 0 )
return;
#ifdef _UNICODE
if( cchDestChar == -1 )
{
wcscpy( wstrDestination, tstrSource );
}
else
{
wcsncpy( wstrDestination, tstrSource, cchDestChar );
wstrDestination[cchDestChar-1] = L'\0';
}
#else
DXUtil_ConvertAnsiStringToWide( wstrDestination, tstrSource, cchDestChar );
#endif
}
//-----------------------------------------------------------------------------
// Name: DXUtil_ConvertAnsiStringToGeneric()
// Desc: This is a UNICODE conversion utility to convert a CHAR string into a
// TCHAR string. cchDestChar defaults -1 which means it
// assumes strDest is large enough to store strSource
//-----------------------------------------------------------------------------
VOID DXUtil_ConvertAnsiStringToGeneric( TCHAR* tstrDestination, const CHAR* strSource,
int cchDestChar )
{
if( tstrDestination==NULL || strSource==NULL || cchDestChar == 0 )
return;
#ifdef _UNICODE
DXUtil_ConvertAnsiStringToWide( tstrDestination, strSource, cchDestChar );
#else
if( cchDestChar == -1 )
{
strcpy( tstrDestination, strSource );
}
else
{
strncpy( tstrDestination, strSource, cchDestChar );
tstrDestination[cchDestChar-1] = '\0';
}
#endif
}
//-----------------------------------------------------------------------------
// Name: DXUtil_ConvertAnsiStringToGeneric()
// Desc: This is a UNICODE conversion utility to convert a WCHAR string into a
// TCHAR string. cchDestChar defaults -1 which means it
// assumes strDest is large enough to store strSource
//-----------------------------------------------------------------------------
VOID DXUtil_ConvertWideStringToGeneric( TCHAR* tstrDestination, const WCHAR* wstrSource,
int cchDestChar )
{
if( tstrDestination==NULL || wstrSource==NULL || cchDestChar == 0 )
return;
#ifdef _UNICODE
if( cchDestChar == -1 )
{
wcscpy( tstrDestination, wstrSource );
}
else
{
wcsncpy( tstrDestination, wstrSource, cchDestChar );
tstrDestination[cchDestChar-1] = L'\0';
}
#else
DXUtil_ConvertWideStringToAnsi( tstrDestination, wstrSource, cchDestChar );
#endif
}
//-----------------------------------------------------------------------------
// Name: _DbgOut()
// Desc: Outputs a message to the debug stream
//-----------------------------------------------------------------------------
HRESULT _DbgOut( TCHAR* strFile, DWORD dwLine, HRESULT hr, TCHAR* strMsg )
{
TCHAR buffer[256];
wsprintf( buffer, _T("%s(%ld): "), strFile, dwLine );
OutputDebugString( buffer );
OutputDebugString( strMsg );
if( hr )
{
wsprintf( buffer, _T("(hr=%08lx)\n"), hr );
OutputDebugString( buffer );
}
OutputDebugString( _T("\n") );
return hr;
}
//-----------------------------------------------------------------------------
// Name: DXUtil_Trace()
// Desc: Outputs to the debug stream a formatted string with a variable-
// argument list.
//-----------------------------------------------------------------------------
VOID DXUtil_Trace( TCHAR* strMsg, ... )
{
#if defined(DEBUG) | defined(_DEBUG)
TCHAR strBuffer[512];
va_list args;
va_start(args, strMsg);
_vsntprintf( strBuffer, 512, strMsg, args );
va_end(args);
OutputDebugString( strBuffer );
#else
UNREFERENCED_PARAMETER(strMsg);
#endif
}
//-----------------------------------------------------------------------------
// Name: DXUtil_ConvertStringToGUID()
// Desc: Converts a string to a GUID
//-----------------------------------------------------------------------------
BOOL DXUtil_ConvertStringToGUID( const TCHAR* strIn, GUID* pGuidOut )
{
UINT aiTmp[10];
if( _stscanf( strIn, TEXT("{%8X-%4X-%4X-%2X%2X-%2X%2X%2X%2X%2X%2X}"),
&pGuidOut->Data1,
&aiTmp[0], &aiTmp[1],
&aiTmp[2], &aiTmp[3],
&aiTmp[4], &aiTmp[5],
&aiTmp[6], &aiTmp[7],
&aiTmp[8], &aiTmp[9] ) != 11 )
{
ZeroMemory( pGuidOut, sizeof(GUID) );
return FALSE;
}
else
{
pGuidOut->Data2 = (USHORT) aiTmp[0];
pGuidOut->Data3 = (USHORT) aiTmp[1];
pGuidOut->Data4[0] = (BYTE) aiTmp[2];
pGuidOut->Data4[1] = (BYTE) aiTmp[3];
pGuidOut->Data4[2] = (BYTE) aiTmp[4];
pGuidOut->Data4[3] = (BYTE) aiTmp[5];
pGuidOut->Data4[4] = (BYTE) aiTmp[6];
pGuidOut->Data4[5] = (BYTE) aiTmp[7];
pGuidOut->Data4[6] = (BYTE) aiTmp[8];
pGuidOut->Data4[7] = (BYTE) aiTmp[9];
return TRUE;
}
}
//-----------------------------------------------------------------------------
// Name: DXUtil_ConvertGUIDToString()
// Desc: Converts a GUID to a string
//-----------------------------------------------------------------------------
VOID DXUtil_ConvertGUIDToString( const GUID* pGuidIn, TCHAR* strOut )
{
_stprintf( strOut, TEXT("{%0.8X-%0.4X-%0.4X-%0.2X%0.2X-%0.2X%0.2X%0.2X%0.2X%0.2X%0.2X}"),
pGuidIn->Data1, pGuidIn->Data2, pGuidIn->Data3,
pGuidIn->Data4[0], pGuidIn->Data4[1],
pGuidIn->Data4[2], pGuidIn->Data4[3],
pGuidIn->Data4[4], pGuidIn->Data4[5],
pGuidIn->Data4[6], pGuidIn->Data4[7] );
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,372 @@
//-----------------------------------------------------------------------------
// File: NetVoice.cpp
//
// Desc: DirectPlay Voice framework class. Feel free to use
// this class as a starting point for adding extra functionality.
//
//
// Copyright (c) 2000-2001 Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#define STRICT
#include <windows.h>
#include <dxerr8.h>
#include <dvoice.h>
#include "NetVoice.h"
#include "DXUtil.h"
//-----------------------------------------------------------------------------
// Name: CNetVoice
// Desc:
//-----------------------------------------------------------------------------
CNetVoice::CNetVoice( LPDVMESSAGEHANDLER pfnDirectPlayClientVoiceMessageHandler,
LPDVMESSAGEHANDLER pfnDirectPlayServerVoiceMessageHandler )
{
m_bHalfDuplex = FALSE;
m_pVoiceClient = NULL;
m_pVoiceServer = NULL;
m_pfnDirectPlayClientVoiceMessageHandler = pfnDirectPlayClientVoiceMessageHandler;
m_pfnDirectPlayServerVoiceMessageHandler = pfnDirectPlayServerVoiceMessageHandler;
}
//-----------------------------------------------------------------------------
// Name: ~CNetVoice
// Desc:
//-----------------------------------------------------------------------------
CNetVoice::~CNetVoice()
{
Free();
}
//-----------------------------------------------------------------------------
// Name: Init()
// Desc: Initializes DirectPlay Voice.
// Params: hDlg: the HWND of the parent window for use by the voice setup wizard
// bCreateSession: if TRUE then it creates the DirectPlay Voice sesson.
// bConnectToSession: if TRUE then it connects to the DirectPlay Voice
// session.
// pDirectPlay: inteface to the IDirectPlay8Client or
// IDirectPlay8Peer interface
// pGuidCT: guid of the voice compression codec
// pdvClientConfig: client config. Can be NULL if bConnectToSession is FALSE.
// lpds: pointer to an existing DirectSound object, or NULL
// if none exists yet.
//-----------------------------------------------------------------------------
HRESULT CNetVoice::Init( HWND hDlg, BOOL bCreateSession, BOOL bConnectToSession,
LPUNKNOWN pDirectPlay, DWORD dwSessionType,
GUID* pGuidCT, DVCLIENTCONFIG* pdvClientConfig, LPDIRECTSOUND lpds )
{
HRESULT hr;
// Typically the host player creates the voice session
if( bCreateSession )
{
if( FAILED( hr = VoiceSessionCreate( pDirectPlay, dwSessionType, pGuidCT ) ) )
return DXTRACE_ERR( TEXT("VoiceSessionCreate"), hr );
}
if( bConnectToSession )
{
// Test the voice setup to make sure the voice setup wizard has been run
if( FAILED( hr = VoiceSessionTestAudioSetup( hDlg ) ) )
{
if( hr == DVERR_USERCANCEL || hr == DVERR_ALREADYPENDING )
return hr;
return DXTRACE_ERR( TEXT("VoiceSessionTestAudioSetup"), hr );
}
// Typically all of the clients connect to the voice session
if( FAILED( hr = VoiceSessionConnect( hDlg, pDirectPlay, pdvClientConfig, lpds ) ) )
return DXTRACE_ERR( TEXT("VoiceSessionConnect"), hr );
}
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: Free()
// Desc: Frees DirectPlayVoice
//-----------------------------------------------------------------------------
HRESULT CNetVoice::Free()
{
HRESULT hr;
if( m_pVoiceClient )
{
// Have all the clients disconnect from the session
if( FAILED( hr = VoiceSessionDisconnect() ) )
return DXTRACE_ERR( TEXT("VoiceSessionDisconnect"), hr );
}
if( m_pVoiceServer )
{
// Have all the host player destroy the session
if( FAILED( hr = VoiceSessionDestroy() ) )
return DXTRACE_ERR( TEXT("VoiceSessionDestroy"), hr );
}
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: HostMigrate()
// Desc: Starts the DirectPlayVoice session
// The host player should call this to create the voice session. It
// stores the server interface, and addref's it.
//-----------------------------------------------------------------------------
HRESULT CNetVoice::HostMigrate( LPDIRECTPLAYVOICESERVER pdvServerInterface )
{
if( pdvServerInterface == NULL )
return E_INVALIDARG;
SAFE_RELEASE( m_pVoiceServer );
m_pVoiceServer = pdvServerInterface;
// Addref the server since we are storing the pointer.
m_pVoiceServer->AddRef();
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: VoiceSessionTestAudioSetup()
// Desc: Uses IDirectPlayVoiceSetup to test the voice setup.
// All clients should call this once to test the voice audio setup.
//-----------------------------------------------------------------------------
HRESULT CNetVoice::VoiceSessionTestAudioSetup( HWND hDlg )
{
HRESULT hr;
LPDIRECTPLAYVOICETEST pVoiceSetup = NULL;
// Create a DirectPlayVoice setup interface.
if( FAILED( hr = CoCreateInstance( CLSID_DirectPlayVoiceTest, NULL,
CLSCTX_INPROC_SERVER,
IID_IDirectPlayVoiceTest,
(LPVOID*) &pVoiceSetup) ) )
return DXTRACE_ERR( TEXT("CoCreateInstance"), hr );
// Check to see if the audio tests have been run yet
GUID guidPlayback = DSDEVID_DefaultVoicePlayback;
GUID guidCapture = DSDEVID_DefaultVoiceCapture;
hr = pVoiceSetup->CheckAudioSetup( &guidPlayback,
&guidCapture,
hDlg, DVFLAGS_QUERYONLY );
if( hr == DVERR_RUNSETUP )
{
// Perform the audio tests, since they need to be done before
// any of the DPVoice calls will work.
hr = pVoiceSetup->CheckAudioSetup( &guidPlayback, &guidCapture, hDlg, DVFLAGS_ALLOWBACK );
if( FAILED(hr) )
{
SAFE_RELEASE( pVoiceSetup );
if( hr == DVERR_USERCANCEL || hr == DVERR_ALREADYPENDING )
return hr;
return DXTRACE_ERR( TEXT("CheckAudioSetup"), hr );
}
}
// Done with setup
SAFE_RELEASE( pVoiceSetup );
return hr;
}
//-----------------------------------------------------------------------------
// Name: VoiceSessionCreate()
// Desc: Starts the DirectPlayVoice session
// The host player should call this to create the voice session.
//-----------------------------------------------------------------------------
HRESULT CNetVoice::VoiceSessionCreate( LPUNKNOWN pDirectPlay, DWORD dwSessionType,
GUID* pGuidCT )
{
HRESULT hr;
// Create a DirectPlayVoice server interface.
if( FAILED( hr = CoCreateInstance( CLSID_DirectPlayVoiceServer, NULL,
CLSCTX_INPROC_SERVER,
IID_IDirectPlayVoiceServer,
(LPVOID*) &m_pVoiceServer ) ) )
return DXTRACE_ERR( TEXT("CoCreateInstance"), hr );
// Init the DirectPlayVoice server
if( FAILED( hr = m_pVoiceServer->Initialize( pDirectPlay, m_pfnDirectPlayServerVoiceMessageHandler,
NULL, 0, 0 ) ) )
return DXTRACE_ERR( TEXT("Initialize"), hr );
// Setup and start a DirectPlay session based on globals set by user choices
// in the config dlg box.
DVSESSIONDESC dvSessionDesc;
ZeroMemory( &dvSessionDesc, sizeof(DVSESSIONDESC) );
dvSessionDesc.dwSize = sizeof( DVSESSIONDESC );
dvSessionDesc.dwBufferAggressiveness = DVBUFFERAGGRESSIVENESS_DEFAULT;
dvSessionDesc.dwBufferQuality = DVBUFFERQUALITY_DEFAULT;
dvSessionDesc.dwFlags = 0;
dvSessionDesc.dwSessionType = dwSessionType;
dvSessionDesc.guidCT = *pGuidCT;
if( FAILED( hr = m_pVoiceServer->StartSession( &dvSessionDesc, 0 ) ) )
return DXTRACE_ERR( TEXT("StartSession"), hr );
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: VoiceSessionConnect()
// Desc: Connects to the DirectPlayVoice session.
/// All clients should call this once to join the voice session.
//-----------------------------------------------------------------------------
HRESULT CNetVoice::VoiceSessionConnect( HWND hDlg, LPUNKNOWN pDirectPlay,
DVCLIENTCONFIG* pdvClientConfig, LPDIRECTSOUND lpds )
{
HRESULT hr;
// Create a DirectPlayVoice client interface.
if( FAILED( hr = CoCreateInstance( CLSID_DirectPlayVoiceClient, NULL,
CLSCTX_INPROC_SERVER,
IID_IDirectPlayVoiceClient,
(LPVOID*) &m_pVoiceClient ) ) )
return DXTRACE_ERR( TEXT("CoCreateInstance"), hr );
// Init the DirectPlayVoice client, passing in VoiceMessageHandler() as the
// callback handler for any messages sent to us.
if( FAILED( hr = m_pVoiceClient->Initialize( pDirectPlay,
m_pfnDirectPlayClientVoiceMessageHandler,
(LPVOID*) hDlg, // context value
0, 0 ) ) )
return DXTRACE_ERR( TEXT("Initialize"), hr );
// Setup the DirectPlayVoice sound devices. This just uses the defaults.
DVSOUNDDEVICECONFIG dvSoundDeviceConfig;
dvSoundDeviceConfig.dwSize = sizeof( DVSOUNDDEVICECONFIG );
dvSoundDeviceConfig.dwFlags = 0;
dvSoundDeviceConfig.guidPlaybackDevice = DSDEVID_DefaultVoicePlayback;
dvSoundDeviceConfig.lpdsPlaybackDevice = lpds;
dvSoundDeviceConfig.guidCaptureDevice = DSDEVID_DefaultVoiceCapture;
dvSoundDeviceConfig.lpdsCaptureDevice = NULL;
dvSoundDeviceConfig.hwndAppWindow = hDlg;
dvSoundDeviceConfig.lpdsMainBuffer = NULL;
dvSoundDeviceConfig.dwMainBufferFlags = 0;
dvSoundDeviceConfig.dwMainBufferPriority = 0;
// Connect to the voice session
if( FAILED( hr = m_pVoiceClient->Connect( &dvSoundDeviceConfig,
pdvClientConfig,
DVFLAGS_SYNC ) ) )
return DXTRACE_ERR( TEXT("Connect"), hr );
// Talk to everyone in the session
DVID dvid = DVID_ALLPLAYERS;
if( FAILED( hr = m_pVoiceClient->SetTransmitTargets( &dvid, 1, 0 ) ) )
return DXTRACE_ERR( TEXT("SetTransmitTargets"), hr );
// Get the sound device config and extract if its half duplex
DWORD dwSize = 0;
DVSOUNDDEVICECONFIG* pdvSoundDeviceConfig = NULL;
hr = m_pVoiceClient->GetSoundDeviceConfig( pdvSoundDeviceConfig, &dwSize );
if( FAILED(hr) && hr != DVERR_BUFFERTOOSMALL )
return DXTRACE_ERR( TEXT("GetSoundDeviceConfig"), hr );
pdvSoundDeviceConfig = (DVSOUNDDEVICECONFIG*) new BYTE[ dwSize ];
ZeroMemory( pdvSoundDeviceConfig, dwSize );
pdvSoundDeviceConfig->dwSize = sizeof(DVSOUNDDEVICECONFIG);
hr = m_pVoiceClient->GetSoundDeviceConfig( pdvSoundDeviceConfig, &dwSize );
if( FAILED(hr) )
return DXTRACE_ERR( TEXT("GetSoundDeviceConfig"), hr );
m_bHalfDuplex = ( (pdvSoundDeviceConfig->dwFlags & DVSOUNDCONFIG_HALFDUPLEX) != 0 );
SAFE_DELETE_ARRAY( pdvSoundDeviceConfig );
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: ChangeVoiceClientSettings()
// Desc: Changes the client config to globals set by user choices
// in the config dlg box.
//-----------------------------------------------------------------------------
HRESULT CNetVoice::ChangeVoiceClientSettings( DVCLIENTCONFIG* pdvClientConfig )
{
HRESULT hr;
if( m_pVoiceClient == NULL )
return CO_E_NOTINITIALIZED;
// Change the client config
if( FAILED( hr = m_pVoiceClient->SetClientConfig( pdvClientConfig) ) )
return DXTRACE_ERR( TEXT("SetClientConfig"), hr );
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: VoiceSessionDisconnect()
// Desc: Disconnects from the DirectPlayVoice session
// All clients should call this once to leave the voice session.
//-----------------------------------------------------------------------------
HRESULT CNetVoice::VoiceSessionDisconnect()
{
if( m_pVoiceClient )
{
m_pVoiceClient->Disconnect( DVFLAGS_SYNC );
SAFE_RELEASE( m_pVoiceClient );
}
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: VoiceSessionDestroy()
// Desc: Stops the DirectPlayVoice session
// The host player should call this once to destroy the voice session.
//-----------------------------------------------------------------------------
HRESULT CNetVoice::VoiceSessionDestroy()
{
if( m_pVoiceServer )
{
m_pVoiceServer->StopSession( 0 );
SAFE_RELEASE( m_pVoiceServer );
}
return S_OK;
}

View File

@@ -0,0 +1,684 @@
//-----------------------------------------------------------------------------
// File: Boids.cpp
//
// Desc:
//
// Copyright (c) 1995-2001 Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#define STRICT
#include <stdio.h>
#include <math.h>
#include <d3dx8.h>
#include "D3DApp.h"
#include "D3DFile.h"
#include "D3DFont.h"
#include "D3DUtil.h"
#include "DXUtil.h"
#include "boids.h"
#include "music.h"
//-----------------------------------------------------------------------------
// Defines, constants, and global variables
//-----------------------------------------------------------------------------
BoidMusic g_Music;
struct BOIDVERTEX
{
D3DXVECTOR3 p;
D3DXVECTOR3 n;
};
struct GRIDVERTEX
{
D3DXVECTOR3 pos;
D3DCOLOR color;
};
#define D3DFVF_BOIDVERTEX (D3DFVF_XYZ|D3DFVF_NORMAL)
#define D3DFVF_GRIDVERTEX (D3DFVF_XYZ|D3DFVF_DIFFUSE)
#define NUM_BOIDS 40
inline FLOAT rnd() { return (((FLOAT)rand())/RAND_MAX); }
inline FLOAT Min( D3DXVECTOR3 v )
{
if( v.x < v.y ) return (v.x < v.z ) ? v.x : v.z;
else return (v.y < v.z ) ? v.y : v.z;
}
inline FLOAT Max( D3DXVECTOR3 v )
{
if( v.x > v.y ) return (v.x > v.z ) ? v.x : v.z;
else return (v.y > v.z ) ? v.y : v.z;
}
BOOL g_bSeparation = FALSE;
BOOL g_bAlignment = FALSE;
BOOL g_bCohesion = FALSE;
BOOL g_bMigratory = FALSE;
BOOL g_bObstacle = FALSE;
//-----------------------------------------------------------------------------
// Name: class CMyD3DApplication
// Desc: Application class. The base class (CD3DApplication) provides the
// generic functionality needed in all Direct3D samples. CMyD3DApplication
// adds functionality specific to this sample program.
//-----------------------------------------------------------------------------
class CMyD3DApplication : public CD3DApplication
{
CD3DFont* m_pFont; // Font for drawing text
D3DXMATRIX m_matWorld; // Transform matrices
D3DXMATRIX m_matView;
D3DXMATRIX m_matProj;
D3DLIGHT8 m_Light1; // Lights and materials
D3DLIGHT8 m_Light2;
D3DMATERIAL8 m_mtrlBackground;
D3DMATERIAL8 m_mtrlGrid;
D3DMATERIAL8 m_mtrlBoid;
CD3DMesh* m_pSphere; // Spheres
FLOAT m_fSphereSpin;
LPDIRECT3DVERTEXBUFFER8 m_pBoidVB; // Boid mesh
LPDIRECT3DINDEXBUFFER8 m_pBoidIB;
BOIDVERTEX m_vBoidVertices[16];
WORD m_wBoidIndices[30];
DWORD m_dwNumBoidVertices;
DWORD m_dwNumBoidIndices;
CFlock m_Flock; // The flock structure
CD3DMesh* m_pSeaGull; // Seagull mesh
GRIDVERTEX m_vGridPattern1[25]; // Grid mesh
GRIDVERTEX m_vGridPattern2[9];
// Internal functions
HRESULT RenderFlock();
protected:
HRESULT OneTimeSceneInit();
HRESULT InitDeviceObjects();
HRESULT RestoreDeviceObjects();
HRESULT InvalidateDeviceObjects();
HRESULT DeleteDeviceObjects();
HRESULT FinalCleanup();
HRESULT Render();
HRESULT FrameMove();
public:
LRESULT MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam );
CMyD3DApplication();
};
//-----------------------------------------------------------------------------
// Name: WinMain()
// Desc: Entry point to the program. Initializes everything, and goes into a
// message-processing loop. Idle time is used to render the scene.
//-----------------------------------------------------------------------------
INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR, INT )
{
CMyD3DApplication d3dApp;
if( FAILED( d3dApp.Create( hInst ) ) )
return 0;
return d3dApp.Run();
}
//-----------------------------------------------------------------------------
// Name: CMyD3DApplication()
// Desc: Application constructor. Sets attributes for the app.
//-----------------------------------------------------------------------------
CMyD3DApplication::CMyD3DApplication()
:CD3DApplication()
{
m_strWindowTitle = _T("DMBoids: DMusic Flocking Boids Sample");
m_bUseDepthBuffer = TRUE;
m_fSphereSpin = 0.0f;
m_pBoidVB = NULL;
m_pBoidIB = NULL;
m_pSphere = new CD3DMesh();
m_pSeaGull = new CD3DMesh();
}
//-----------------------------------------------------------------------------
// Name:
// Desc:
//-----------------------------------------------------------------------------
HRESULT CMyD3DApplication::OneTimeSceneInit()
{
D3DXVECTOR3 vNorm;
// generate the boid data
m_dwNumBoidVertices = 16;
m_dwNumBoidIndices = 30;
// top
m_vBoidVertices[ 0].p = D3DXVECTOR3( 0.0f, 0.0f, 10.0f); D3DXVec3Normalize( &m_vBoidVertices[ 0].n, &D3DXVECTOR3( 0.2f, 1.0f, 0.0f) );
m_vBoidVertices[ 1].p = D3DXVECTOR3( 10.0f, 0.0f,-10.0f); D3DXVec3Normalize( &m_vBoidVertices[ 1].n, &D3DXVECTOR3( 0.1f, 1.0f, 0.0f) );
m_vBoidVertices[ 2].p = D3DXVECTOR3( 3.0f, 3.0f, -7.0f); D3DXVec3Normalize( &m_vBoidVertices[ 2].n, &D3DXVECTOR3( 0.0f, 1.0f, 0.0f) );
m_vBoidVertices[ 3].p = D3DXVECTOR3( -3.0f, 3.0f, -7.0f); D3DXVec3Normalize( &m_vBoidVertices[ 3].n, &D3DXVECTOR3(-0.1f, 1.0f, 0.0f) );
m_vBoidVertices[ 4].p = D3DXVECTOR3(-10.0f, 0.0f,-10.0f); D3DXVec3Normalize( &m_vBoidVertices[ 4].n, &D3DXVECTOR3(-0.2f, 1.0f, 0.0f) );
// bottom
m_vBoidVertices[ 5].p = D3DXVECTOR3( 0.0f, 0.0f, 10.0f); D3DXVec3Normalize( &m_vBoidVertices[ 5].n, &D3DXVECTOR3( 0.2f, -1.0f, 0.0f) );
m_vBoidVertices[ 6].p = D3DXVECTOR3( 10.0f, 0.0f,-10.0f); D3DXVec3Normalize( &m_vBoidVertices[ 6].n, &D3DXVECTOR3( 0.1f, -1.0f, 0.0f) );
m_vBoidVertices[ 7].p = D3DXVECTOR3( 3.0f,-3.0f, -7.0f); D3DXVec3Normalize( &m_vBoidVertices[ 7].n, &D3DXVECTOR3( 0.0f, -1.0f, 0.0f) );
m_vBoidVertices[ 8].p = D3DXVECTOR3( -3.0f,-3.0f, -7.0f); D3DXVec3Normalize( &m_vBoidVertices[ 8].n, &D3DXVECTOR3(-0.1f, -1.0f, 0.0f) );
m_vBoidVertices[ 9].p = D3DXVECTOR3(-10.0f, 0.0f,-10.0f); D3DXVec3Normalize( &m_vBoidVertices[ 9].n, &D3DXVECTOR3(-0.2f, -1.0f, 0.0f) );
// rear
m_vBoidVertices[10].p = D3DXVECTOR3( 10.0f, 0.0f,-10.0f); D3DXVec3Normalize( &m_vBoidVertices[10].n, &D3DXVECTOR3(-0.4f, 0.0f, -1.0f) );
m_vBoidVertices[11].p = D3DXVECTOR3( 3.0f, 3.0f, -7.0f); D3DXVec3Normalize( &m_vBoidVertices[11].n, &D3DXVECTOR3(-0.2f, 0.0f, -1.0f) );
m_vBoidVertices[12].p = D3DXVECTOR3( -3.0f, 3.0f, -7.0f); D3DXVec3Normalize( &m_vBoidVertices[12].n, &D3DXVECTOR3( 0.2f, 0.0f, -1.0f) );
m_vBoidVertices[13].p = D3DXVECTOR3(-10.0f, 0.0f,-10.0f); D3DXVec3Normalize( &m_vBoidVertices[13].n, &D3DXVECTOR3( 0.4f, 0.0f, -1.0f) );
m_vBoidVertices[14].p = D3DXVECTOR3( -3.0f,-3.0f, -7.0f); D3DXVec3Normalize( &m_vBoidVertices[14].n, &D3DXVECTOR3( 0.2f, 0.0f, -1.0f) );
m_vBoidVertices[15].p = D3DXVECTOR3( 3.0f,-3.0f, -7.0f); D3DXVec3Normalize( &m_vBoidVertices[15].n, &D3DXVECTOR3(-0.2f, 0.0f, -1.0f) );
// top
m_wBoidIndices[ 0] = 0; m_wBoidIndices[ 1] = 1; m_wBoidIndices[ 2] = 2;
m_wBoidIndices[ 3] = 0; m_wBoidIndices[ 4] = 2; m_wBoidIndices[ 5] = 3;
m_wBoidIndices[ 6] = 0; m_wBoidIndices[ 7] = 3; m_wBoidIndices[ 8] = 4;
// bottom
m_wBoidIndices[ 9] = 5; m_wBoidIndices[10] = 7; m_wBoidIndices[11] = 6;
m_wBoidIndices[12] = 5; m_wBoidIndices[13] = 8; m_wBoidIndices[14] = 7;
m_wBoidIndices[15] = 5; m_wBoidIndices[16] = 9; m_wBoidIndices[17] = 8;
// rear
m_wBoidIndices[18] = 10; m_wBoidIndices[19] = 15; m_wBoidIndices[20] = 11;
m_wBoidIndices[21] = 11; m_wBoidIndices[22] = 15; m_wBoidIndices[23] = 12;
m_wBoidIndices[24] = 12; m_wBoidIndices[25] = 15; m_wBoidIndices[26] = 14;
m_wBoidIndices[27] = 12; m_wBoidIndices[28] = 14; m_wBoidIndices[29] = 13;
// scale the boid to be unit length
for( DWORD i=0; i<16; i++ )
{
m_vBoidVertices[i].p.x /= 20.0f;
m_vBoidVertices[i].p.y /= 20.0f;
m_vBoidVertices[i].p.z /= 20.0f;
}
// seed the random number generator
srand( timeGetTime() );
// allocate the flock
m_Flock.m_Boids = new Boid[NUM_BOIDS];
m_Flock.m_dwNumBoids = NUM_BOIDS;
m_Flock.m_afDist = (FLOAT**)new LPVOID[NUM_BOIDS];
m_Flock.m_vGoal = D3DXVECTOR3( 0.0f, 0.0f, 0.0f );
for( i=0; i<m_Flock.m_dwNumBoids; i++ )
{
D3DXMatrixIdentity( &m_Flock.m_Boids[i].matWorld );
m_Flock.m_Boids[i].vPos = D3DXVECTOR3( 200.0f*(rnd()-rnd()), 100.0f*rnd(), 200.0f*(rnd()-rnd()) );
D3DXVec3Normalize( &m_Flock.m_Boids[i].vDir, &D3DXVECTOR3(rnd()-rnd(), rnd()-rnd(), rnd()-rnd()));
m_Flock.m_Boids[i].yaw = 0.0f;
m_Flock.m_Boids[i].pitch = 0.0f;
m_Flock.m_Boids[i].roll = 0.0f;
m_Flock.m_Boids[i].dyaw = 0.0f;
m_Flock.m_Boids[i].speed = 0.1f;
m_Flock.m_Boids[i].color = D3DXVECTOR3( rnd(), rnd(), rnd() );
m_Flock.m_Boids[i].color -= D3DXVECTOR3( Min(m_Flock.m_Boids[i].color), Min(m_Flock.m_Boids[i].color), Min(m_Flock.m_Boids[i].color) );
m_Flock.m_Boids[i].color /= Max( m_Flock.m_Boids[i].color );
m_Flock.m_afDist[i] = new FLOAT[NUM_BOIDS];
}
m_Flock.m_dwNumObstacles = 4;
m_Flock.m_Obstacles = new Obstacle[m_Flock.m_dwNumObstacles];
m_Flock.m_Obstacles[0].vPos = D3DXVECTOR3( 100.0f, 10.0f, 0.0f );
m_Flock.m_Obstacles[1].vPos = D3DXVECTOR3( 0.0f, 10.0f, 100.0f );
m_Flock.m_Obstacles[2].vPos = D3DXVECTOR3(-100.0f, 10.0f, 0.0f );
m_Flock.m_Obstacles[3].vPos = D3DXVECTOR3( 0.0f, 10.0f,-100.0f );
m_Flock.m_Obstacles[0].fRadius = 0.2f;
m_Flock.m_Obstacles[1].fRadius = 0.2f;
m_Flock.m_Obstacles[2].fRadius = 0.2f;
m_Flock.m_Obstacles[3].fRadius = 0.2f;
D3DCOLOR diffuse = D3DCOLOR_RGBA( 0, 0, 30, 128 );
D3DCOLOR specular = D3DCOLOR_RGBA( 0, 0, 0, 0 );
for( i=0; i<=24; i++ )
m_vGridPattern1[i].color = diffuse;
m_vGridPattern1[ 0].pos = D3DXVECTOR3(-25.0f, 0.0f, 35.0f );
m_vGridPattern1[ 1].pos = D3DXVECTOR3(-15.0f, 0.0f, 35.0f );
m_vGridPattern1[ 2].pos = D3DXVECTOR3( -5.0f, 0.0f, 25.0f );
m_vGridPattern1[ 3].pos = D3DXVECTOR3( 5.0f, 0.0f, 25.0f );
m_vGridPattern1[ 4].pos = D3DXVECTOR3( 15.0f, 0.0f, 35.0f );
m_vGridPattern1[ 5].pos = D3DXVECTOR3( 25.0f, 0.0f, 35.0f );
m_vGridPattern1[ 6].pos = D3DXVECTOR3( 35.0f, 0.0f, 25.0f );
m_vGridPattern1[ 7].pos = D3DXVECTOR3( 35.0f, 0.0f, 15.0f );
m_vGridPattern1[ 8].pos = D3DXVECTOR3( 25.0f, 0.0f, 5.0f );
m_vGridPattern1[ 9].pos = D3DXVECTOR3( 25.0f, 0.0f, -5.0f );
m_vGridPattern1[10].pos = D3DXVECTOR3( 35.0f, 0.0f,-15.0f );
m_vGridPattern1[11].pos = D3DXVECTOR3( 35.0f, 0.0f,-25.0f );
m_vGridPattern1[12].pos = D3DXVECTOR3( 25.0f, 0.0f,-35.0f );
m_vGridPattern1[13].pos = D3DXVECTOR3( 15.0f, 0.0f,-35.0f );
m_vGridPattern1[14].pos = D3DXVECTOR3( 5.0f, 0.0f,-25.0f );
m_vGridPattern1[15].pos = D3DXVECTOR3( -5.0f, 0.0f,-25.0f );
m_vGridPattern1[16].pos = D3DXVECTOR3(-15.0f, 0.0f,-35.0f );
m_vGridPattern1[17].pos = D3DXVECTOR3(-25.0f, 0.0f,-35.0f );
m_vGridPattern1[18].pos = D3DXVECTOR3(-35.0f, 0.0f,-25.0f );
m_vGridPattern1[19].pos = D3DXVECTOR3(-35.0f, 0.0f,-15.0f );
m_vGridPattern1[20].pos = D3DXVECTOR3(-25.0f, 0.0f, -5.0f );
m_vGridPattern1[21].pos = D3DXVECTOR3(-25.0f, 0.0f, 5.0f );
m_vGridPattern1[22].pos = D3DXVECTOR3(-35.0f, 0.0f, 15.0f );
m_vGridPattern1[23].pos = D3DXVECTOR3(-35.0f, 0.0f, 25.0f );
m_vGridPattern1[24].pos = D3DXVECTOR3(-25.0f, 0.0f, 35.0f );
for( i=0; i<=8; i++ )
m_vGridPattern2[i].color = diffuse;
m_vGridPattern2[0].pos = D3DXVECTOR3( -5.0f, 0.0f, 15.0f );
m_vGridPattern2[1].pos = D3DXVECTOR3( 5.0f, 0.0f, 15.0f );
m_vGridPattern2[2].pos = D3DXVECTOR3( 15.0f, 0.0f, 5.0f );
m_vGridPattern2[3].pos = D3DXVECTOR3( 15.0f, 0.0f, -5.0f );
m_vGridPattern2[4].pos = D3DXVECTOR3( 5.0f, 0.0f,-15.0f );
m_vGridPattern2[5].pos = D3DXVECTOR3( -5.0f, 0.0f,-15.0f );
m_vGridPattern2[6].pos = D3DXVECTOR3(-15.0f, 0.0f, -5.0f );
m_vGridPattern2[7].pos = D3DXVECTOR3(-15.0f, 0.0f, 5.0f );
m_vGridPattern2[8].pos = D3DXVECTOR3( -5.0f, 0.0f, 15.0f );
if( FAILED( g_Music.LoadMusic( m_hWnd ) ) )
{
OutputDebugString("Failed to initialize DirectMusic.\n");
return E_FAIL;
}
g_Music.StartMusic();
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: FrameMove()
// Desc:
//-----------------------------------------------------------------------------
HRESULT CMyD3DApplication::FrameMove()
{
D3DXVECTOR3 vEyePt;
D3DXVECTOR3 vLookAtPt( 0.0f, 0.0f, 0.0f );
D3DXVECTOR3 vUp( 0.0f, 1.0f, 0.0f );
FLOAT fTime;
FLOAT fElapsedTime;
// The REF device is slow enough to throw off the animation
// in this sample, so if using the REF device, simulate
// running at 20fps regardless of actual rendering speed.
if( m_d3dCaps.DeviceType == D3DDEVTYPE_REF )
{
static FLOAT fTimePrev = 0.0f;
fElapsedTime = 0.05f;
fTime = fTimePrev + fElapsedTime;
fTimePrev = fTime;
}
else
{
fElapsedTime = m_fElapsedTime;
fTime = m_fTime;
}
// Move each boids to its new location
m_Flock.Update( fElapsedTime );
// LookAt point is the center of the flock
for( DWORD i=0; i<m_Flock.m_dwNumBoids; i++ )
vLookAtPt += m_Flock.m_Boids[i].vPos;
vLookAtPt /= (FLOAT)m_Flock.m_dwNumBoids;
vEyePt = vLookAtPt + 40 * D3DXVECTOR3( sinf(fTime*0.111f),
0.70f+0.75f*sinf(fTime*0.163f),
cosf(fTime*0.155f) );
D3DXMatrixLookAtLH( &m_matView, &vEyePt, &vLookAtPt, &vUp );
g_Music.SetDistance( D3DXVec3Length( &( vEyePt - vLookAtPt ) ) );
// Update the flock's goal
m_Flock.m_vGoal = 100.0f * D3DXVECTOR3( sinf(fTime*0.1f), 0.1f, cosf(fTime*0.1f) );
m_fSphereSpin = fTime;
g_Music.HandleNotifies();
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: RenderFlock()
// Desc:
//-----------------------------------------------------------------------------
HRESULT CMyD3DApplication::RenderFlock()
{
// Set the view and projection matrices
m_pd3dDevice->SetTransform( D3DTS_VIEW, &m_matView );
m_pd3dDevice->SetTransform( D3DTS_PROJECTION, &m_matProj );
// Draw ground grid
m_pd3dDevice->SetMaterial( &m_mtrlGrid );
for (int dx= -2; dx<3; dx++)
{
for (int dz= -2; dz<3; dz++)
{
D3DXMatrixTranslation( &m_matWorld, dx*80.0f, 0.0f, dz*80.0f );
m_pd3dDevice->SetTransform( D3DTS_WORLD, &m_matWorld );
m_pd3dDevice->SetVertexShader( D3DFVF_GRIDVERTEX );
m_pd3dDevice->DrawPrimitiveUP( D3DPT_LINESTRIP, 24, m_vGridPattern1,
sizeof(GRIDVERTEX) );
m_pd3dDevice->DrawPrimitiveUP( D3DPT_LINESTRIP, 8, m_vGridPattern2,
sizeof(GRIDVERTEX) );
}
}
// Draw the boids
for( DWORD i=0; i<m_Flock.m_dwNumBoids; i++ )
{
// Most of the time display the boid
if( i%13 || m_d3dCaps.DeviceType == D3DDEVTYPE_REF )
{
// Set the boid's world matrix
m_pd3dDevice->SetTransform( D3DTS_WORLD, &m_Flock.m_Boids[i].matWorld );
// Set the boid's color
m_mtrlBoid.Diffuse.r = m_Flock.m_Boids[i].color.x;
m_mtrlBoid.Diffuse.g = m_Flock.m_Boids[i].color.y;
m_mtrlBoid.Diffuse.b = m_Flock.m_Boids[i].color.z;
m_pd3dDevice->SetMaterial( &m_mtrlBoid );
// Render the boid
m_pd3dDevice->SetVertexShader( D3DFVF_BOIDVERTEX );
m_pd3dDevice->SetStreamSource( 0, m_pBoidVB, sizeof(BOIDVERTEX) );
m_pd3dDevice->SetIndices( m_pBoidIB, 0L );
m_pd3dDevice->DrawIndexedPrimitive( D3DPT_TRIANGLELIST,
0, m_dwNumBoidVertices,
0, m_dwNumBoidIndices/3 );
}
else
{
// Set the matrix
D3DXMATRIX matWorld, matRotateY;
D3DXMatrixRotationY( &matRotateY, D3DX_PI );
D3DXMatrixMultiply( &matWorld, &matRotateY, &m_Flock.m_Boids[i].matWorld );
m_pd3dDevice->SetTransform( D3DTS_WORLD, &matWorld );
// Display a seagull
m_pSeaGull->Render( m_pd3dDevice );
}
}
for( i=0; i<m_Flock.m_dwNumObstacles; i++ )
{
D3DXMATRIX matRotate, matScale;
FLOAT fScale = m_Flock.m_Obstacles[i].fRadius;
D3DXMatrixRotationY( &matRotate, m_fSphereSpin );
D3DXMatrixScaling( &matScale, fScale, fScale, fScale );
D3DXMatrixMultiply( &m_matWorld, &matScale, &matRotate );
m_matWorld._41 = m_Flock.m_Obstacles[i].vPos.x;
m_matWorld._42 = m_Flock.m_Obstacles[i].vPos.y;
m_matWorld._43 = m_Flock.m_Obstacles[i].vPos.z;
m_pd3dDevice->SetTransform( D3DTS_WORLD, &m_matWorld );
m_pSphere->Render( m_pd3dDevice );
}
return S_OK;
}
//-----------------------------------------------------------------------------
// Name:
// Desc:
//-----------------------------------------------------------------------------
HRESULT CMyD3DApplication::Render()
{
// Clear the scene to black
m_pd3dDevice->Clear( 0L, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER,
0x00000000, 1.0f, 0L );
// Begin Scene
if( FAILED( m_pd3dDevice->BeginScene() ) )
return S_OK;
RenderFlock();
m_pd3dDevice->EndScene();
return S_OK;
}
//-----------------------------------------------------------------------------
// Name:
// Desc:
//-----------------------------------------------------------------------------
HRESULT CMyD3DApplication::InitDeviceObjects()
{
if( FAILED( m_pSphere->Create( m_pd3dDevice, _T("orbiter.x") ) ) )
return D3DAPPERR_MEDIANOTFOUND;
if( FAILED( m_pSeaGull->Create( m_pd3dDevice, _T("Shusui.x") ) ) )
return D3DAPPERR_MEDIANOTFOUND;
// Create a VB for the boids
if( FAILED( m_pd3dDevice->CreateVertexBuffer( m_dwNumBoidVertices*sizeof(BOIDVERTEX),
D3DUSAGE_WRITEONLY, D3DFVF_BOIDVERTEX,
D3DPOOL_MANAGED, &m_pBoidVB ) ) )
return E_FAIL;
BOIDVERTEX* v;
m_pBoidVB->Lock( 0, 0, (BYTE**)&v, 0 );
memcpy( v, m_vBoidVertices, m_dwNumBoidVertices*sizeof(BOIDVERTEX) );
m_pBoidVB->Unlock();
// Create an IB for the boids
if( FAILED( m_pd3dDevice->CreateIndexBuffer( m_dwNumBoidIndices*sizeof(WORD),
D3DUSAGE_WRITEONLY, D3DFMT_INDEX16,
D3DPOOL_MANAGED, &m_pBoidIB ) ) )
return E_FAIL;
WORD* i;
m_pBoidIB->Lock( 0, 0, (BYTE**)&i, 0 );
memcpy( i, m_wBoidIndices, m_dwNumBoidIndices*sizeof(WORD) );
m_pBoidIB->Unlock();
return S_OK;
}
//-----------------------------------------------------------------------------
// Name:
// Desc:
//-----------------------------------------------------------------------------
HRESULT CMyD3DApplication::RestoreDeviceObjects()
{
m_pSphere->RestoreDeviceObjects( m_pd3dDevice );
m_pSeaGull->RestoreDeviceObjects( m_pd3dDevice );
// Set up transform matrices
D3DXVECTOR3 vEyePt = D3DXVECTOR3( 0.0f, 0.0f, -100.0f );
D3DXVECTOR3 vLookAtPt = D3DXVECTOR3( 0.0f, 0.0f, 0.0f );
D3DXVECTOR3 vUp = D3DXVECTOR3( 0.0f, 1.0f, 0.0f );
D3DXMatrixIdentity( &m_matWorld );
D3DXMatrixLookAtLH( &m_matView, &vEyePt, &vLookAtPt, &vUp );
D3DXMatrixPerspectiveFovLH( &m_matProj, D3DX_PI/4, 1.0f, 5.0f, 400.0f );
// Setup materials
D3DUtil_InitMaterial( m_mtrlBackground, 0.0f, 0.0f, 0.0f );
D3DUtil_InitMaterial( m_mtrlGrid, 0.0f, 0.0f, 0.0f );
m_mtrlGrid.Emissive.r = 0.0f;
m_mtrlGrid.Emissive.g = 0.3f;
m_mtrlGrid.Emissive.b = 0.5f;
D3DUtil_InitMaterial( m_mtrlBoid, 1.0f, 1.0f, 1.0f );
// Create 2 lights
D3DUtil_InitLight( m_Light1, D3DLIGHT_DIRECTIONAL, -0.5f, -1.0f, -0.3f );
D3DUtil_InitLight( m_Light2, D3DLIGHT_DIRECTIONAL, 0.5f, 1.0f, 0.3f );
m_Light2.Diffuse.r = 0.5f;
m_Light2.Diffuse.g = 0.5f;
m_Light2.Diffuse.b = 0.5f;
m_pd3dDevice->SetLight( 0, &m_Light1 );
m_pd3dDevice->SetLight( 1, &m_Light2 );
m_pd3dDevice->LightEnable( 0, TRUE );
m_pd3dDevice->LightEnable( 1, TRUE );
// Set render state
m_pd3dDevice->SetRenderState( D3DRS_SPECULARENABLE, FALSE );
m_pd3dDevice->SetRenderState( D3DRS_ZENABLE, TRUE );
m_pd3dDevice->SetRenderState( D3DRS_DITHERENABLE, TRUE );
m_pd3dDevice->SetRenderState( D3DRS_AMBIENT, 0x11111111 );
return S_OK;
}
//-----------------------------------------------------------------------------
// Name:
// Desc:
//-----------------------------------------------------------------------------
HRESULT CMyD3DApplication::InvalidateDeviceObjects()
{
m_pSphere->InvalidateDeviceObjects();
m_pSeaGull->InvalidateDeviceObjects();
return S_OK;
}
//-----------------------------------------------------------------------------
// Name:
// Desc:
//-----------------------------------------------------------------------------
HRESULT CMyD3DApplication::DeleteDeviceObjects()
{
m_pSphere->Destroy();
m_pSeaGull->Destroy();
SAFE_RELEASE( m_pBoidVB );
SAFE_RELEASE( m_pBoidIB );
return S_OK;
}
//-----------------------------------------------------------------------------
// Name:
// Desc:
//-----------------------------------------------------------------------------
HRESULT CMyD3DApplication::FinalCleanup()
{
for( int i=0; i<NUM_BOIDS; i++ )
{
SAFE_DELETE_ARRAY( m_Flock.m_afDist[i] );
}
SAFE_DELETE_ARRAY( m_Flock.m_Boids );
SAFE_DELETE_ARRAY( m_Flock.m_afDist );
SAFE_DELETE_ARRAY( m_Flock.m_Obstacles );
SAFE_DELETE( m_pSphere );
SAFE_DELETE( m_pSeaGull );
g_Music.EndMusic();
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: MsgProc()
// Desc: Message proc function to handle key and menu input
//-----------------------------------------------------------------------------
LRESULT CMyD3DApplication::MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam,
LPARAM lParam )
{
// Handle menu commands
if( WM_KEYDOWN==uMsg || WM_KEYUP==uMsg )
{
switch( wParam )
{
case 'A':
g_bAlignment = (WM_KEYDOWN==uMsg);
break;
case 'C':
g_bCohesion = (WM_KEYDOWN==uMsg);
break;
case 'O':
g_bObstacle = (WM_KEYDOWN==uMsg);
break;
case 'M':
g_bMigratory = (WM_KEYDOWN==uMsg);
if( g_bMigratory )
g_Music.Migrate();
break;
case 'S':
g_bSeparation = (WM_KEYDOWN==uMsg);
if( g_bSeparation )
g_Music.Collapse();
else
g_Music.Expand();
break;
}
}
else if( WM_ACTIVATE==uMsg )
{
g_Music.Activate( LOWORD( wParam ) != WA_INACTIVE );
}
// Pass remaining messages to default handler
return CD3DApplication::MsgProc( hWnd, uMsg, wParam, lParam );
}

View File

@@ -0,0 +1,79 @@
//-----------------------------------------------------------------------------
// File: Boids.h
//
// Desc:
//
// Copyright (c) 1995-2001 Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#ifndef BOIDS_H
#define BOIDS_H
//-----------------------------------------------------------------------------
// Name:
// Desc:
//-----------------------------------------------------------------------------
class Boid
{
public:
D3DXMATRIX matWorld; // matrix representing the boids location/orientation
D3DXVECTOR3 vPos; // location
D3DXVECTOR3 vDir; // cur direction
D3DXVECTOR3 vSeparationForce;
D3DXVECTOR3 vAlignmentForce;
D3DXVECTOR3 vCohesionForce;
D3DXVECTOR3 vMigratoryForce;
D3DXVECTOR3 vObstacleForce;
DWORD dwNumNeighbors;
D3DXVECTOR3 vDeltaPos; // change in position from flock centering
D3DXVECTOR3 vDeltaDir; // change in direction
int iDeltaCnt; // number of boids that influence this delta_dir
FLOAT speed;
FLOAT yaw, pitch, roll, dyaw;
D3DXVECTOR3 color;
};
//-----------------------------------------------------------------------------
// Name:
// Desc:
//-----------------------------------------------------------------------------
struct Obstacle
{
D3DXVECTOR3 vPos;
FLOAT fRadius;
};
//-----------------------------------------------------------------------------
// Name:
// Desc:
//-----------------------------------------------------------------------------
class CFlock
{
public:
DWORD m_dwNumBoids;
Boid* m_Boids;
DWORD m_dwNumObstacles;
Obstacle* m_Obstacles;
FLOAT** m_afDist; // 2-d array of boid distances, yuk what a waste
D3DXVECTOR3 m_vGoal;
// Functions
VOID Update( FLOAT fElapsedTime );
};
#endif

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

View File

@@ -0,0 +1,136 @@
# Microsoft Developer Studio Project File - Name="DMBoids" - Package Owner=<4>
# Microsoft Developer Studio Generated Build File, Format Version 6.00
# ** DO NOT EDIT **
# TARGTYPE "Win32 (x86) Application" 0x0101
CFG=DMBoids - Win32 Debug
!MESSAGE This is not a valid makefile. To build this project using NMAKE,
!MESSAGE use the Export Makefile command and run
!MESSAGE
!MESSAGE NMAKE /f "dmboids.mak".
!MESSAGE
!MESSAGE You can specify a configuration when running NMAKE
!MESSAGE by defining the macro CFG on the command line. For example:
!MESSAGE
!MESSAGE NMAKE /f "dmboids.mak" CFG="DMBoids - Win32 Debug"
!MESSAGE
!MESSAGE Possible choices for configuration are:
!MESSAGE
!MESSAGE "DMBoids - Win32 Release" (based on "Win32 (x86) Application")
!MESSAGE "DMBoids - Win32 Debug" (based on "Win32 (x86) Application")
!MESSAGE
# Begin Project
# PROP AllowPerConfigDependencies 0
# PROP Scc_ProjName ""
# PROP Scc_LocalPath ""
CPP=cl.exe
MTL=midl.exe
RSC=rc.exe
!IF "$(CFG)" == "DMBoids - Win32 Release"
# PROP BASE Use_MFC 0
# PROP BASE Use_Debug_Libraries 0
# PROP BASE Output_Dir "Release"
# PROP BASE Intermediate_Dir "Release"
# PROP BASE Target_Dir ""
# PROP Use_MFC 0
# PROP Use_Debug_Libraries 0
# PROP Output_Dir "Release"
# PROP Intermediate_Dir "Release"
# PROP Ignore_Export_Lib 0
# PROP Target_Dir ""
# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /YX /FD /c
# ADD CPP /nologo /W3 /GX /O2 /I "..\..\common\include" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /YX /FD /c
# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /o "NUL" /win32
# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /o "NUL" /win32
# ADD BASE RSC /l 0x409 /d "NDEBUG"
# ADD RSC /l 0x409 /d "NDEBUG"
BSC32=bscmake.exe
# ADD BASE BSC32 /nologo
# ADD BSC32 /nologo
LINK32=link.exe
# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /subsystem:windows /machine:I386
# ADD LINK32 d3dx8.lib d3d8.lib d3dxof.lib dinput.lib dxguid.lib winspool.lib oleaut32.lib uuid.lib dxerr8.lib ole32.lib winmm.lib kernel32.lib user32.lib gdi32.lib comdlg32.lib advapi32.lib shell32.lib /nologo /subsystem:windows /machine:I386 /stack:0x1f4000,0x1f4000
!ELSEIF "$(CFG)" == "DMBoids - Win32 Debug"
# PROP BASE Use_MFC 0
# PROP BASE Use_Debug_Libraries 1
# PROP BASE Output_Dir "Debug"
# PROP BASE Intermediate_Dir "Debug"
# PROP BASE Target_Dir ""
# PROP Use_MFC 0
# PROP Use_Debug_Libraries 1
# PROP Output_Dir "Debug"
# PROP Intermediate_Dir "Debug"
# PROP Ignore_Export_Lib 0
# PROP Target_Dir ""
# ADD BASE CPP /nologo /W3 /Gm /GX /Zi /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /YX /FD /c
# ADD CPP /nologo /W3 /Gm /GX /Zi /Od /I "..\..\common\include" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /FD /c
# SUBTRACT CPP /YX
# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /o "NUL" /win32
# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /o "NUL" /win32
# ADD BASE RSC /l 0x409 /d "_DEBUG"
# ADD RSC /l 0x409 /d "_DEBUG"
BSC32=bscmake.exe
# ADD BASE BSC32 /nologo
# ADD BSC32 /nologo
LINK32=link.exe
# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /subsystem:windows /debug /machine:I386 /pdbtype:sept
# ADD LINK32 d3dx8dt.lib d3d8.lib d3dxof.lib dinput.lib dxguid.lib winspool.lib oleaut32.lib uuid.lib dxerr8.lib ole32.lib winmm.lib kernel32.lib user32.lib gdi32.lib comdlg32.lib advapi32.lib shell32.lib /nologo /subsystem:windows /debug /machine:I386 /pdbtype:sept /stack:0x1f4000,0x1f4000
!ENDIF
# Begin Target
# Name "DMBoids - Win32 Release"
# Name "DMBoids - Win32 Debug"
# Begin Group "Common"
# PROP Default_Filter ""
# Begin Source File
SOURCE=..\..\common\src\d3dapp.cpp
# End Source File
# Begin Source File
SOURCE=..\..\common\src\d3dfile.cpp
# End Source File
# Begin Source File
SOURCE=..\..\common\src\d3dfont.cpp
# End Source File
# Begin Source File
SOURCE=..\..\common\src\d3dutil.cpp
# End Source File
# Begin Source File
SOURCE=..\..\common\src\dmutil.cpp
# End Source File
# Begin Source File
SOURCE=..\..\common\src\dxutil.cpp
# End Source File
# End Group
# Begin Source File
SOURCE=.\boids.cpp
# End Source File
# Begin Source File
SOURCE=.\dmboids.rc
# End Source File
# Begin Source File
SOURCE=.\flock.cpp
# End Source File
# Begin Source File
SOURCE=.\music.cpp
# End Source File
# End Target
# End Project

View File

@@ -0,0 +1,29 @@
Microsoft Developer Studio Workspace File, Format Version 6.00
# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE!
###############################################################################
Project: "DMBoids"=.\dmboids.dsp - Package Owner=<4>
Package=<5>
{{{
}}}
Package=<4>
{{{
}}}
###############################################################################
Global:
Package=<5>
{{{
}}}
Package=<3>
{{{
}}}
###############################################################################

View File

@@ -0,0 +1,279 @@
# Microsoft Developer Studio Generated NMAKE File, Based on dmboids.dsp
!IF "$(CFG)" == ""
CFG=DMBoids - Win32 Debug
!MESSAGE No configuration specified. Defaulting to DMBoids - Win32 Debug.
!ENDIF
!IF "$(CFG)" != "DMBoids - Win32 Release" && "$(CFG)" != "DMBoids - Win32 Debug"
!MESSAGE Invalid configuration "$(CFG)" specified.
!MESSAGE You can specify a configuration when running NMAKE
!MESSAGE by defining the macro CFG on the command line. For example:
!MESSAGE
!MESSAGE NMAKE /f "dmboids.mak" CFG="DMBoids - Win32 Debug"
!MESSAGE
!MESSAGE Possible choices for configuration are:
!MESSAGE
!MESSAGE "DMBoids - Win32 Release" (based on "Win32 (x86) Application")
!MESSAGE "DMBoids - Win32 Debug" (based on "Win32 (x86) Application")
!MESSAGE
!ERROR An invalid configuration is specified.
!ENDIF
!IF "$(OS)" == "Windows_NT"
NULL=
!ELSE
NULL=nul
!ENDIF
!IF "$(CFG)" == "DMBoids - Win32 Release"
OUTDIR=.\Release
INTDIR=.\Release
# Begin Custom Macros
OutDir=.\Release
# End Custom Macros
ALL : "$(OUTDIR)\dmboids.exe"
CLEAN :
-@erase "$(INTDIR)\boids.obj"
-@erase "$(INTDIR)\d3dapp.obj"
-@erase "$(INTDIR)\d3dfile.obj"
-@erase "$(INTDIR)\d3dfont.obj"
-@erase "$(INTDIR)\d3dutil.obj"
-@erase "$(INTDIR)\dmboids.res"
-@erase "$(INTDIR)\dmutil.obj"
-@erase "$(INTDIR)\dxutil.obj"
-@erase "$(INTDIR)\flock.obj"
-@erase "$(INTDIR)\music.obj"
-@erase "$(INTDIR)\vc60.idb"
-@erase "$(OUTDIR)\dmboids.exe"
"$(OUTDIR)" :
if not exist "$(OUTDIR)/$(NULL)" mkdir "$(OUTDIR)"
CPP=cl.exe
CPP_PROJ=/nologo /ML /W3 /GX /O2 /I "..\..\common\include" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /Fp"$(INTDIR)\dmboids.pch" /YX /Fo"$(INTDIR)\\" /Fd"$(INTDIR)\\" /FD /c
.c{$(INTDIR)}.obj::
$(CPP) @<<
$(CPP_PROJ) $<
<<
.cpp{$(INTDIR)}.obj::
$(CPP) @<<
$(CPP_PROJ) $<
<<
.cxx{$(INTDIR)}.obj::
$(CPP) @<<
$(CPP_PROJ) $<
<<
.c{$(INTDIR)}.sbr::
$(CPP) @<<
$(CPP_PROJ) $<
<<
.cpp{$(INTDIR)}.sbr::
$(CPP) @<<
$(CPP_PROJ) $<
<<
.cxx{$(INTDIR)}.sbr::
$(CPP) @<<
$(CPP_PROJ) $<
<<
MTL=midl.exe
MTL_PROJ=/nologo /D "NDEBUG" /mktyplib203 /o "NUL" /win32
RSC=rc.exe
RSC_PROJ=/l 0x409 /fo"$(INTDIR)\dmboids.res" /d "NDEBUG"
BSC32=bscmake.exe
BSC32_FLAGS=/nologo /o"$(OUTDIR)\dmboids.bsc"
BSC32_SBRS= \
LINK32=link.exe
LINK32_FLAGS=d3dx8.lib d3d8.lib d3dxof.lib dinput.lib dxguid.lib winspool.lib oleaut32.lib uuid.lib dxerr8.lib ole32.lib winmm.lib kernel32.lib user32.lib gdi32.lib comdlg32.lib advapi32.lib shell32.lib /nologo /subsystem:windows /incremental:no /pdb:"$(OUTDIR)\dmboids.pdb" /machine:I386 /out:"$(OUTDIR)\dmboids.exe"
LINK32_OBJS= \
"$(INTDIR)\d3dapp.obj" \
"$(INTDIR)\d3dfile.obj" \
"$(INTDIR)\d3dfont.obj" \
"$(INTDIR)\d3dutil.obj" \
"$(INTDIR)\dmutil.obj" \
"$(INTDIR)\dxutil.obj" \
"$(INTDIR)\boids.obj" \
"$(INTDIR)\flock.obj" \
"$(INTDIR)\music.obj" \
"$(INTDIR)\dmboids.res"
"$(OUTDIR)\dmboids.exe" : "$(OUTDIR)" $(DEF_FILE) $(LINK32_OBJS)
$(LINK32) @<<
$(LINK32_FLAGS) $(LINK32_OBJS)
<<
!ELSEIF "$(CFG)" == "DMBoids - Win32 Debug"
OUTDIR=.\Debug
INTDIR=.\Debug
# Begin Custom Macros
OutDir=.\Debug
# End Custom Macros
ALL : "$(OUTDIR)\dmboids.exe"
CLEAN :
-@erase "$(INTDIR)\boids.obj"
-@erase "$(INTDIR)\d3dapp.obj"
-@erase "$(INTDIR)\d3dfile.obj"
-@erase "$(INTDIR)\d3dfont.obj"
-@erase "$(INTDIR)\d3dutil.obj"
-@erase "$(INTDIR)\dmboids.res"
-@erase "$(INTDIR)\dmutil.obj"
-@erase "$(INTDIR)\dxutil.obj"
-@erase "$(INTDIR)\flock.obj"
-@erase "$(INTDIR)\music.obj"
-@erase "$(INTDIR)\vc60.idb"
-@erase "$(INTDIR)\vc60.pdb"
-@erase "$(OUTDIR)\dmboids.exe"
-@erase "$(OUTDIR)\dmboids.ilk"
-@erase "$(OUTDIR)\dmboids.pdb"
"$(OUTDIR)" :
if not exist "$(OUTDIR)/$(NULL)" mkdir "$(OUTDIR)"
CPP=cl.exe
CPP_PROJ=/nologo /MLd /W3 /Gm /GX /Zi /Od /I "..\..\common\include" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /Fo"$(INTDIR)\\" /Fd"$(INTDIR)\\" /FD /c
.c{$(INTDIR)}.obj::
$(CPP) @<<
$(CPP_PROJ) $<
<<
.cpp{$(INTDIR)}.obj::
$(CPP) @<<
$(CPP_PROJ) $<
<<
.cxx{$(INTDIR)}.obj::
$(CPP) @<<
$(CPP_PROJ) $<
<<
.c{$(INTDIR)}.sbr::
$(CPP) @<<
$(CPP_PROJ) $<
<<
.cpp{$(INTDIR)}.sbr::
$(CPP) @<<
$(CPP_PROJ) $<
<<
.cxx{$(INTDIR)}.sbr::
$(CPP) @<<
$(CPP_PROJ) $<
<<
MTL=midl.exe
MTL_PROJ=/nologo /D "_DEBUG" /mktyplib203 /o "NUL" /win32
RSC=rc.exe
RSC_PROJ=/l 0x409 /fo"$(INTDIR)\dmboids.res" /d "_DEBUG"
BSC32=bscmake.exe
BSC32_FLAGS=/nologo /o"$(OUTDIR)\dmboids.bsc"
BSC32_SBRS= \
LINK32=link.exe
LINK32_FLAGS=d3dx8dt.lib d3d8.lib d3dxof.lib dinput.lib dxguid.lib winspool.lib oleaut32.lib uuid.lib dxerr8.lib ole32.lib winmm.lib kernel32.lib user32.lib gdi32.lib comdlg32.lib advapi32.lib shell32.lib /nologo /subsystem:windows /incremental:yes /pdb:"$(OUTDIR)\dmboids.pdb" /debug /machine:I386 /out:"$(OUTDIR)\dmboids.exe" /pdbtype:sept
LINK32_OBJS= \
"$(INTDIR)\d3dapp.obj" \
"$(INTDIR)\d3dfile.obj" \
"$(INTDIR)\d3dfont.obj" \
"$(INTDIR)\d3dutil.obj" \
"$(INTDIR)\dmutil.obj" \
"$(INTDIR)\dxutil.obj" \
"$(INTDIR)\boids.obj" \
"$(INTDIR)\flock.obj" \
"$(INTDIR)\music.obj" \
"$(INTDIR)\dmboids.res"
"$(OUTDIR)\dmboids.exe" : "$(OUTDIR)" $(DEF_FILE) $(LINK32_OBJS)
$(LINK32) @<<
$(LINK32_FLAGS) $(LINK32_OBJS)
<<
!ENDIF
!IF "$(NO_EXTERNAL_DEPS)" != "1"
!IF EXISTS("dmboids.dep")
!INCLUDE "dmboids.dep"
!ELSE
!MESSAGE Warning: cannot find "dmboids.dep"
!ENDIF
!ENDIF
!IF "$(CFG)" == "DMBoids - Win32 Release" || "$(CFG)" == "DMBoids - Win32 Debug"
SOURCE=..\..\common\src\d3dapp.cpp
"$(INTDIR)\d3dapp.obj" : $(SOURCE) "$(INTDIR)"
$(CPP) $(CPP_PROJ) $(SOURCE)
SOURCE=..\..\common\src\d3dfile.cpp
"$(INTDIR)\d3dfile.obj" : $(SOURCE) "$(INTDIR)"
$(CPP) $(CPP_PROJ) $(SOURCE)
SOURCE=..\..\common\src\d3dfont.cpp
"$(INTDIR)\d3dfont.obj" : $(SOURCE) "$(INTDIR)"
$(CPP) $(CPP_PROJ) $(SOURCE)
SOURCE=..\..\common\src\d3dutil.cpp
"$(INTDIR)\d3dutil.obj" : $(SOURCE) "$(INTDIR)"
$(CPP) $(CPP_PROJ) $(SOURCE)
SOURCE=..\..\common\src\dmutil.cpp
"$(INTDIR)\dmutil.obj" : $(SOURCE) "$(INTDIR)"
$(CPP) $(CPP_PROJ) $(SOURCE)
SOURCE=..\..\common\src\dxutil.cpp
"$(INTDIR)\dxutil.obj" : $(SOURCE) "$(INTDIR)"
$(CPP) $(CPP_PROJ) $(SOURCE)
SOURCE=.\boids.cpp
"$(INTDIR)\boids.obj" : $(SOURCE) "$(INTDIR)"
SOURCE=.\dmboids.rc
"$(INTDIR)\dmboids.res" : $(SOURCE) "$(INTDIR)"
$(RSC) $(RSC_PROJ) $(SOURCE)
SOURCE=.\flock.cpp
"$(INTDIR)\flock.obj" : $(SOURCE) "$(INTDIR)"
SOURCE=.\music.cpp
"$(INTDIR)\music.obj" : $(SOURCE) "$(INTDIR)"
!ENDIF

View File

@@ -0,0 +1,211 @@
//Microsoft Developer Studio generated resource script.
//
#include "resource.h"
#define APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 2 resource.
//
#define IDC_STATIC -1
#include <windows.h>
/////////////////////////////////////////////////////////////////////////////
#undef APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
// English (U.S.) resources
#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
#ifdef _WIN32
LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
#pragma code_page(1252)
#endif //_WIN32
/////////////////////////////////////////////////////////////////////////////
//
// Icon
//
// Icon with lowest ID value placed first to ensure application icon
// remains consistent on all systems.
IDI_MAIN_ICON ICON DISCARDABLE "DirectX.ico"
#ifdef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// TEXTINCLUDE
//
1 TEXTINCLUDE DISCARDABLE
BEGIN
"resource.h\0"
END
2 TEXTINCLUDE DISCARDABLE
BEGIN
"#define IDC_STATIC -1\r\n"
"#include <windows.h>\r\n"
"\r\n"
"\r\n"
"\0"
END
3 TEXTINCLUDE DISCARDABLE
BEGIN
"\r\n"
"\0"
END
#endif // APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// Accelerator
//
IDR_MAIN_ACCEL ACCELERATORS DISCARDABLE
BEGIN
VK_ESCAPE, IDM_EXIT, VIRTKEY, NOINVERT
VK_F1, IDM_ABOUT, VIRTKEY, NOINVERT
VK_F2, IDM_CHANGEDEVICE, VIRTKEY, NOINVERT
VK_RETURN, IDM_TOGGLESTART, VIRTKEY, NOINVERT
VK_RETURN, IDM_TOGGLEFULLSCREEN, VIRTKEY, ALT, NOINVERT
VK_SPACE, IDM_SINGLESTEP, VIRTKEY, NOINVERT
"X", IDM_EXIT, VIRTKEY, ALT, NOINVERT
END
/////////////////////////////////////////////////////////////////////////////
//
// DESIGNINFO
//
#ifdef APSTUDIO_INVOKED
GUIDELINES DESIGNINFO DISCARDABLE
BEGIN
IDD_ABOUT, DIALOG
BEGIN
LEFTMARGIN, 7
RIGHTMARGIN, 165
TOPMARGIN, 7
BOTTOMMARGIN, 104
END
IDD_SELECTDEVICE, DIALOG
BEGIN
LEFTMARGIN, 7
RIGHTMARGIN, 259
TOPMARGIN, 7
BOTTOMMARGIN, 109
END
END
#endif // APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// Dialog
//
IDD_ABOUT DIALOG DISCARDABLE 0, 0, 172, 111
STYLE DS_SYSMODAL | DS_MODALFRAME | DS_NOIDLEMSG | DS_SETFOREGROUND |
DS_3DLOOK | DS_CENTER | WS_POPUP | WS_VISIBLE | WS_CAPTION
CAPTION "About"
FONT 8, "MS Shell Dlg"
BEGIN
DEFPUSHBUTTON "OK",IDOK,115,90,40,14
ICON IDI_MAIN_ICON,IDC_STATIC,5,5,20,20
LTEXT "Direct3D Sample",IDC_STATIC,35,5,54,8
LTEXT "Copyright (c) 1998-1999 Microsoft Corp.",IDC_STATIC,35,
15,126,8
LTEXT "About",IDC_STATIC,60,40,20,8
LTEXT "Select Driver / Device / Mode",IDC_STATIC,60,50,97,8
CTEXT "<Alt+Enter>",IDC_STATIC,10,60,45,8
LTEXT "Toggle Fullscreen / Windowed",IDC_STATIC,60,60,98,8
LTEXT "Exit",IDC_STATIC,60,70,12,8
CTEXT "<F1>",IDC_STATIC,10,40,45,8
CTEXT "<F2>",IDC_STATIC,10,50,45,8
CTEXT "<ESC>",IDC_STATIC,10,70,45,8
GROUPBOX "Usage",IDC_STATIC,5,30,160,55
END
IDD_SELECTDEVICE DIALOG DISCARDABLE 0, 0, 267, 116
STYLE DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU
CAPTION "Select Device"
FONT 8, "MS Shell Dlg"
BEGIN
COMBOBOX IDC_ADAPTER_COMBO,90,15,105,100,CBS_DROPDOWNLIST |
WS_VSCROLL | WS_TABSTOP
COMBOBOX IDC_DEVICE_COMBO,90,30,105,100,CBS_DROPDOWNLIST |
WS_VSCROLL | WS_TABSTOP
CONTROL "Use desktop &window",IDC_WINDOW,"Button",
BS_AUTORADIOBUTTON | WS_GROUP | WS_TABSTOP,10,60,85,15
CONTROL "&Fullscreen mode",IDC_FULLSCREEN,"Button",
BS_AUTORADIOBUTTON,10,75,75,15
CONTROL "Fullscreen &stereo",IDC_STEREO,"Button",
BS_AUTORADIOBUTTON,10,90,75,15
COMBOBOX IDC_FULLSCREENMODES_COMBO,90,75,105,100,CBS_DROPDOWNLIST |
WS_VSCROLL | WS_GROUP | WS_TABSTOP
COMBOBOX IDC_STEREOMODES_COMBO,90,90,105,100,CBS_DROPDOWNLIST |
WS_VSCROLL | WS_TABSTOP
DEFPUSHBUTTON "OK",IDOK,210,10,50,14
PUSHBUTTON "Cancel",IDCANCEL,210,30,50,14
GROUPBOX "Rendering device",IDC_STATIC,5,5,200,45
LTEXT "&Adapter:",IDC_STATIC,20,15,65,10,SS_CENTERIMAGE
LTEXT "D3D &device:",IDC_STATIC,20,30,65,11,SS_CENTERIMAGE
GROUPBOX "Rendering mode",IDC_STATIC,5,50,200,60
END
/////////////////////////////////////////////////////////////////////////////
//
// Menu
//
IDR_MENU MENU DISCARDABLE
BEGIN
POPUP "&File"
BEGIN
MENUITEM "&Go/stop\tEnter", IDM_TOGGLESTART
MENUITEM "&Single step\tSpace", IDM_SINGLESTEP
MENUITEM SEPARATOR
MENUITEM "&About...\tF1", IDM_ABOUT
MENUITEM "&Change device...\tF2", IDM_CHANGEDEVICE
MENUITEM SEPARATOR
MENUITEM "E&xit\tESC", IDM_EXIT
END
END
IDR_POPUP MENU DISCARDABLE
BEGIN
POPUP "Popup"
BEGIN
MENUITEM "&Go/stop", IDM_TOGGLESTART
MENUITEM "&Single step", IDM_SINGLESTEP
MENUITEM SEPARATOR
MENUITEM "&About...", IDM_ABOUT
MENUITEM "&Change device...", IDM_CHANGEDEVICE
MENUITEM SEPARATOR
MENUITEM "E&xit", IDM_EXIT
END
END
#endif // English (U.S.) resources
/////////////////////////////////////////////////////////////////////////////
#ifndef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 3 resource.
//
/////////////////////////////////////////////////////////////////////////////
#endif // not APSTUDIO_INVOKED

View File

@@ -0,0 +1,270 @@
//-----------------------------------------------------------------------------
// File: Flock.cpp
//
// Desc:
//
// Copyright (c) 1995-2001 Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#include <D3DX8.h>
#include <stdio.h>
#include "DXUtil.h"
#include "boids.h"
#include "music.h"
const float g_fInfluenceRadius = 10.0f; // outside of this range forces are considered to be 0
const float CollisionFraction = 0.8f;
const float InvCollisionFraction = 1.0f/(1.0f-CollisionFraction);
const float g_fNormalSpeed = 0.1f;
const float AngleTweak = 0.02f;
const float g_fPitchToSpeedRatio = 0.002f;
// More arbitray constants that look cool
const float fSeparationScale = 0.05f;
const float fAlignmentScale = 0.1f;
const float fCohesionScale = 1.0f;
const float fMigratoryScale = 0.4f;
const float fObstacleScale = 1.0f;
//-----------------------------------------------------------------------------
// Effects
//-----------------------------------------------------------------------------
extern BoidMusic g_Music;
extern BOOL g_bSeparation;
extern BOOL g_bAlignment;
extern BOOL g_bCohesion;
extern BOOL g_bMigratory;
extern BOOL g_bObstacle;
//-----------------------------------------------------------------------------
// Name:
// Desc:
//-----------------------------------------------------------------------------
VOID CFlock::Update( FLOAT fElapsedTime )
{
DWORD i, j;
static DWORD lastobj = 0xffffffff;
// First, update the dist array 0.0..1.0 with 0.0 being furthest away
for( i=0; i<m_dwNumBoids; i++ )
{
for( j=i+1; j<m_dwNumBoids; j++ )
{
D3DXVECTOR3 vDiff = m_Boids[i].vPos - m_Boids[j].vPos;
FLOAT fDist = D3DXVec3Length( &vDiff );
m_afDist[i][j] = m_afDist[j][i] = fDist;
}
m_afDist[i][i] = 0.0f;
// Reset boid forces
m_Boids[i].vSeparationForce = D3DXVECTOR3( 0.0f, 0.0f, 0.0f );
m_Boids[i].vAlignmentForce = D3DXVECTOR3( 0.0f, 0.0f, 0.0f );
m_Boids[i].vCohesionForce = D3DXVECTOR3( 0.0f, 0.0f, 0.0f );
m_Boids[i].vMigratoryForce = D3DXVECTOR3( 0.0f, 0.0f, 0.0f );
m_Boids[i].vObstacleForce = D3DXVECTOR3( 0.0f, 0.0f, 0.0f );
m_Boids[i].dwNumNeighbors = 0;
}
// For each boid calculate the individual forces affecting it
for( i=0; i<m_dwNumBoids; i++ )
{
// Add in effects from other boids
for( j=i+1; j<m_dwNumBoids; j++ )
{
D3DXVECTOR3 vDiff = m_Boids[i].vPos - m_Boids[j].vPos;
FLOAT fDist = D3DXVec3Length( &vDiff );
// if i is near j have them influence each other
if( fDist < g_fInfluenceRadius )
{
// Sum seperation force
m_Boids[i].vSeparationForce += vDiff/(fDist*fDist);
m_Boids[j].vSeparationForce -= vDiff/(fDist*fDist);
// sum alignment force (actually summing the directions of the neighbors)
m_Boids[i].vAlignmentForce += m_Boids[j].vDir / fDist;
m_Boids[j].vAlignmentForce += m_Boids[i].vDir / fDist;
// sum cohesion force (actually we're summing neighbor locations)
m_Boids[i].vCohesionForce += m_Boids[j].vPos;
m_Boids[j].vCohesionForce += m_Boids[i].vPos;
m_Boids[i].dwNumNeighbors++;
m_Boids[j].dwNumNeighbors++;
}
}
// Add in any obstacle forces
for( j=0; j<m_dwNumObstacles; j++ )
{
D3DXVECTOR3 vDiff = m_Boids[i].vPos - m_Obstacles[j].vPos;
FLOAT fObRadius = m_Obstacles[j].fRadius * 1.5f;
// Ignore object if already past
if( D3DXVec3Dot( &vDiff, &m_Boids[i].vDir ) > 0.0f )
continue;
FLOAT fDist = D3DXVec3Length( &vDiff ) - fObRadius;
if( fDist < g_fInfluenceRadius )
{
if( ( lastobj != j ) && ( fDist < 5.0f ) )
{
lastobj = j;
g_Music.Transition();
}
vDiff /= fDist; // normalize
fDist -= fObRadius;
if( fDist < 0.01f )
fDist = 0.01f;
m_Boids[i].vObstacleForce += vDiff;
}
}
// Find cohesion force
if( m_Boids[i].dwNumNeighbors )
{
m_Boids[i].vCohesionForce /= (FLOAT)m_Boids[i].dwNumNeighbors; // Find average location of neighbors
D3DXVECTOR3 vDiff = m_Boids[i].vCohesionForce - m_Boids[i].vPos; // Find delta to center of flock
FLOAT fMag = D3DXVec3Length( &vDiff );
if( fMag > 0.0f)
m_Boids[i].vCohesionForce = vDiff/fMag; // normalized
else
m_Boids[i].vCohesionForce = D3DXVECTOR3( 0.0f, 0.0f, 0.0f );
}
// Find the alignment force
if( m_Boids[i].dwNumNeighbors != 0 )
{
m_Boids[i].vAlignmentForce /= (FLOAT)m_Boids[i].dwNumNeighbors;
FLOAT fMag = D3DXVec3Length( &m_Boids[i].vAlignmentForce );
if( fMag > 0.0f )
{
m_Boids[i].vAlignmentForce /= fMag; // normalize
D3DXVECTOR3 vDiff = m_Boids[i].vAlignmentForce - m_Boids[i].vDir;
m_Boids[i].vAlignmentForce = vDiff / fMag;
}
}
// Finally, the migratory force
m_Boids[i].vMigratoryForce = m_vGoal - m_Boids[i].vPos;
D3DXVec3Normalize( &m_Boids[i].vMigratoryForce, &m_Boids[i].vMigratoryForce );
}
// Update the boids
for( i=0; i<m_dwNumBoids; i++ )
{
// Sum all the forces
D3DXVECTOR3 vForce( 0.0f, 0.0f, 0.0f );
if( !g_bObstacle ) vForce += m_Boids[i].vObstacleForce;
if( !g_bSeparation ) vForce += m_Boids[i].vSeparationForce;
if( !g_bAlignment ) vForce += m_Boids[i].vAlignmentForce * fAlignmentScale;
if( !g_bCohesion ) vForce += m_Boids[i].vCohesionForce;
if( !g_bMigratory ) vForce += m_Boids[i].vMigratoryForce;
// Ok, now we have a final force to apply to the boid.
// Normalize it if too big.
FLOAT mag = D3DXVec3Length( &vForce );
if( mag > 1.0f )
vForce /= mag;
// first deal with pitch changes
if( vForce.y > 0.01f )
{ // we're too low
m_Boids[i].pitch += AngleTweak;
if (m_Boids[i].pitch > 0.8f)
m_Boids[i].pitch = 0.8f;
}
else if( vForce.y < -0.01f )
{ // we're too high
m_Boids[i].pitch -= AngleTweak;
if (m_Boids[i].pitch < -0.8f)
m_Boids[i].pitch = -0.8f;
}
else
{
// add damping
m_Boids[i].pitch *= 0.98f;
}
// speed up or slow down depending on angle of attack
m_Boids[i].speed -= m_Boids[i].pitch * g_fPitchToSpeedRatio;
// damp back to normal
m_Boids[i].speed = (m_Boids[i].speed-g_fNormalSpeed)*0.99f + g_fNormalSpeed;
// limit speed changes to +- 50% from normal
if( m_Boids[i].speed < g_fNormalSpeed/2 )
m_Boids[i].speed = g_fNormalSpeed/2;
if( m_Boids[i].speed > g_fNormalSpeed*5 )
m_Boids[i].speed = g_fNormalSpeed*5;
// now figure out yaw changes
D3DXVECTOR3 vOffset = vForce;
vOffset.y = 0.0f;
D3DXVECTOR3 vDelta = m_Boids[i].vDir;
if( D3DXVec3Length( &vOffset ) > 0.0f )
D3DXVec3Normalize( &vOffset, &vOffset );
float dot = D3DXVec3Dot( &vOffset, &vDelta );
// speed up slightly if not turning much
if (dot > 0.7f)
{
dot -= 0.7f;
m_Boids[i].speed += dot * 0.005f;
}
D3DXVec3Cross( &vOffset, &vOffset, &vDelta );
// D3DXVec3Cross( &vOffset, &vDelta, &vOffset );
dot = (1.0f-dot)/2.0f * 0.07f;
if( vOffset.y > 0.05f )
{
m_Boids[i].dyaw = (m_Boids[i].dyaw*19.0f + dot) * 0.05f;
}
else if( vOffset.y < -0.05f )
{
m_Boids[i].dyaw = (m_Boids[i].dyaw*19.0f - dot) * 0.05f;
}
else
{
m_Boids[i].dyaw *= 0.98f; // damp it
}
m_Boids[i].yaw += m_Boids[i].dyaw;
m_Boids[i].roll = -m_Boids[i].dyaw * 20.0f;
// Take new info and create a new world matrix
// First translate into place, then set orientation, then scale (if needed)
D3DXMATRIX matTrans, matRotateX, matRotateY, matRotateZ, matTemp1, matTemp2;
D3DXMatrixTranslation( &matTrans, m_Boids[i].vPos.x, m_Boids[i].vPos.y, m_Boids[i].vPos.z );
D3DXMatrixRotationX( &matRotateX, -m_Boids[i].pitch );
D3DXMatrixRotationY( &matRotateY, -m_Boids[i].yaw );
D3DXMatrixRotationZ( &matRotateZ, -m_Boids[i].roll );
D3DXMatrixMultiply( &matTemp1, &matRotateX, &matRotateY );
D3DXMatrixMultiply( &matTemp2, &matRotateZ, &matTemp1 );
D3DXMatrixMultiply( &m_Boids[i].matWorld, &matTemp2, &matTrans );
// Now extract the boid's direction out of the matrix
m_Boids[i].vDir.x = m_Boids[i].matWorld._31;
m_Boids[i].vDir.y = m_Boids[i].matWorld._32;
m_Boids[i].vDir.z = m_Boids[i].matWorld._33;
// And update the boid's location
m_Boids[i].vPos += m_Boids[i].vDir * m_Boids[i].speed * 100 * fElapsedTime;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,116 @@
//-----------------------------------------------------------------------------
// File: Music.h
//
// Desc:
//
// Copyright (c) 1995-2001 Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#ifndef MUSIC_H
#define MUSIC_H
#include <windows.h>
#include <dmusicc.h>
#include <dmusici.h>
interface IDirectMusicStyle;
interface IDirectMusicChordMap;
interface IDirectMusicPerformance;
interface IDirectMusicSegment;
interface IDirectMusicComposer;
interface IDirectMusicLoader;
interface IDirectMusicGraph;
interface IDirectMusicBand;
//-----------------------------------------------------------------------------
// Name:
// Desc:
//-----------------------------------------------------------------------------
class CTool : public IDirectMusicTool
{
public:
CTool();
~CTool();
public:
// IUnknown
virtual STDMETHODIMP QueryInterface(const IID &iid, void **ppv);
virtual STDMETHODIMP_(ULONG) AddRef();
virtual STDMETHODIMP_(ULONG) Release();
// IDirectMusicTool
HRESULT STDMETHODCALLTYPE Init(IDirectMusicGraph* pGraph) ;
HRESULT STDMETHODCALLTYPE GetMsgDeliveryType(DWORD* pdwDeliveryType ) ;
HRESULT STDMETHODCALLTYPE GetMediaTypeArraySize(DWORD* pdwNumElements ) ;
HRESULT STDMETHODCALLTYPE GetMediaTypes(DWORD** padwMediaTypes, DWORD dwNumElements) ;
HRESULT STDMETHODCALLTYPE ProcessPMsg(IDirectMusicPerformance* pPerf, DMUS_PMSG* pPMSG) ;
HRESULT STDMETHODCALLTYPE Flush(IDirectMusicPerformance* pPerf, DMUS_PMSG* pPMSG, REFERENCE_TIME rt) ;
long m_cRef;
DWORD m_dwRatio;
DWORD m_dwEcho;
DWORD m_dwDelay;
DWORD m_dwStartRatio;
IDirectMusicPerformance * m_pPerformance;
};
//-----------------------------------------------------------------------------
// Name:
// Desc:
//-----------------------------------------------------------------------------
class BoidMusic
{
public:
BoidMusic();
~BoidMusic();
HRESULT LoadMusic( HWND hWnd );
BOOL LoadChordMap();
BOOL LoadStyle();
BOOL LoadSegment();
HRESULT LoadDLS();
BOOL LoadTemplate(DWORD dwIndex, WCHAR * pszName);
BOOL GetMotif(DWORD dwIndex, WCHAR * pszName);
void ComposeSegment(DWORD dwIndex);
void EndMusic();
void StartMusic();
void Transition();
void Collapse();
void Expand();
void Migrate();
void HandleNotifies();
void SetDistance(double fDistance);
BOOL GetSearchPath(WCHAR path[MAX_PATH]);
void Activate(BOOL bActive);
IDirectMusicStyle* m_pStyle;
IDirectMusicChordMap* m_pChordMap;
IDirectMusicSegment* m_pTemplateSegments[6];
IDirectMusicSegment* m_pPrimarySegments[6];
IDirectMusicSegment* m_pTransitionSegment;
IDirectMusicSegment* m_pMotifSegments[6];
IDirectMusicSegment* m_pSegment;
IDirectMusicComposer* m_pComposer;
IDirectMusicLoader* m_pLoader;
IDirectMusicPerformance* m_pPerformance;
IDirectMusicGraph* m_pGraph;
IDirectMusicPort* m_pPort;
IDirectMusicBand* m_pBand;
IDirectMusic* m_pDMusic;
DWORD m_dwIndex;
HANDLE m_hNotify;
DWORD m_dwLevel;
CTool m_Tool;
BOOL m_dwBeatsSinceLastMotif;
BOOL m_fCollapsed;
};
#endif

View File

@@ -0,0 +1,58 @@
//-----------------------------------------------------------------------------
//
// Sample Name: DMBoids Sample
//
// Copyright <20> 1999-2001 Microsoft Corp. All Rights Reserved.
//
// GM/GS<47> Sound Set Copyright <20>1996, Roland Corporation U.S.
//
//-----------------------------------------------------------------------------
Description
===========
DMBoids is a version of Boids that adds DirectMusic support. As objects fly
over a simple landscape, the music responds to user input and events on the
screen.
Path
====
Source: DXSDK\Samples\Multimedia\Dmusic\DMBoids
Executable: DXSDK\Samples\Multimedia\DMusic\Bin
User's Guide
============
Press F10 to access the main menu. The Drivers menu allows you to change the
driver, device, and video mode. The application runs only in full-screen
modes.
The A (alignment), C (cohesion) and O (obstacle) keys alter behavior of the
boids in various ways as long as they are held down.
Hold down the S key or the spacebar and the birds flock in closer. Release
the key and they spread apart. Note the use of motifs to track this
behavior.
Hold down the M key and the birds wander off their path. Notice that the
music completely changes. Release and the birds will eventually get back on
the path.
Press the ESC key to quit.
Programming Notes
=================
DirectMusic features illustrated include the following:
 Software synthesis with DLS. In addition to the musical instruments
from the GS sound set, the application uses custom downloadable sounds
such as the voices that appear to come from the planets.
 Composing and performing style-based segments.
 Musical transitions using style-based motifs and segment cues.
 Echo/articulation tool coded that uses the proximity of the birds to
adjust the echoes and note durations of the music as it plays.

View File

@@ -0,0 +1,40 @@
//{{NO_DEPENDENCIES}}
// Microsoft Developer Studio generated include file.
// Used by WinMain.rc
//
#define IDI_MAIN_ICON 101
#define IDR_MAIN_ACCEL 113
#define IDR_MENU 141
#define IDR_POPUP 142
#define IDD_ABOUT 143
#define IDD_CHANGEDEVICE 144
#define IDD_SELECTDEVICE 144
#define IDC_DEVICE_COMBO 1000
#define IDC_MODE_COMBO 1001
#define IDC_ADAPTER_COMBO 1002
#define IDC_FULLSCREENMODES_COMBO 1003
#define IDC_STEREOMODES_COMBO 1004
#define IDC_WINDOWED_CHECKBOX 1012
#define IDC_STEREO_CHECKBOX 1013
#define IDC_FULLSCREEN_TEXT 1014
#define IDC_WINDOW 1016
#define IDC_STEREO 1017
#define IDC_FULLSCREEN 1018
#define IDM_ABOUT 40001
#define IDM_CHANGEDEVICE 40002
#define IDM_TOGGLEFULLSCREEN 40003
#define IDM_TOGGLESTART 40004
#define IDM_SINGLESTEP 40005
#define IDM_EXIT 40006
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_3D_CONTROLS 1
#define _APS_NEXT_RESOURCE_VALUE 146
#define _APS_NEXT_COMMAND_VALUE 40011
#define _APS_NEXT_CONTROL_VALUE 1027
#define _APS_NEXT_SYMED_VALUE 102
#endif
#endif

Binary file not shown.

After

Width:  |  Height:  |  Size: 768 KiB

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,544 @@
//-----------------------------------------------------------------------------
// File: Donuts.h
//
// Desc: Header for Donuts3D game
//
// Copyright (C) 1995-2001 Microsoft Corporation. All Rights Reserved.
//-----------------------------------------------------------------------------
#ifndef DONUTS_H
#define DONUTS_H
//-----------------------------------------------------------------------------
// Defines, and constants
//-----------------------------------------------------------------------------
// This GUID must be unique for every game, and the same for
// every instance of this app. // {2014BAAC-F1FD-458e-9091-0F85C8CF6AFE}
// The GUID allows DirectInput to remember input settings
GUID g_guidApp = { 0x2014baac, 0xf1fd, 0x458e, { 0x90, 0x91, 0xf, 0x85, 0xc8, 0xcf, 0x6a, 0xfe } };
// Error codes
#define DONUTS3DERR_NODIRECT3D 0x00000001
#define DONUTS3DERR_NOD3DDEVICE 0x00000002
#define DONUTS3DERR_NOTEXTURES 0x00000003
#define DONUTS3DERR_NOGEOMETRY 0x00000004
#define DONUTS3DERR_NO3DRESOURCES 0x00000005
#define DONUTS3DERR_NOINPUT 0x00000006
// States the app can be in
enum{ APPSTATE_LOADSPLASH, APPSTATE_DISPLAYSPLASH, APPSTATE_ACTIVE,
APPSTATE_BEGINLEVELSCREEN, APPSTATE_DISPLAYLEVELSCREEN };
// Game object types
enum{ OBJ_DONUT=0, OBJ_PYRAMID, OBJ_CUBE, OBJ_SPHERE, OBJ_CLOUD, OBJ_SHIP,
OBJ_BULLET };
// Object dimensions and fixed properties
#define DONUT_WIDTH 32
#define DONUT_HEIGHT 32
#define PYRAMID_WIDTH 32
#define PYRAMID_HEIGHT 32
#define SPHERE_WIDTH 16
#define SPHERE_HEIGHT 16
#define CUBE_WIDTH 16
#define CUBE_HEIGHT 16
#define CLOUD_WIDTH 32
#define CLOUD_HEIGHT 32
#define BULLET_WIDTH 3
#define BULLET_HEIGHT 3
#define NUM_DONUT_FRAMES 30
#define NUM_PYRAMID_FRAMES 40
#define NUM_SPHERE_FRAMES 40
#define NUM_CUBE_FRAMES 40
#define NUM_BULLET_FRAMES 400
#define BULLET_XOFFSET 304
#define BULLET_YOFFSET 0
// Defines for the in-game menu
#define MENU_MAIN 1
#define MENU_SOUND 2
#define MENU_VIDEO 3
#define MENU_INPUT 4
#define MENU_VIEWDEVICES 5
#define MENU_CONFIGDEVICES 6
#define MENU_WINDOWED 7
#define MENU_640x480 8
#define MENU_800x600 9
#define MENU_1024x768 10
#define MENU_BACK 11
#define MENU_SOUNDON 12
#define MENU_SOUNDOFF 13
#define MENU_QUIT 14
TCHAR* g_strShipFiles[] = { _T("Concept Plane 3.x"), _T("Spaceship 2.x"), _T("Shusui.x"),
_T("Space Station 7.x"), _T("Spaceship 8.x"), _T("Orbiter.x"),
_T("Spaceship 13.x"), _T("Spaceship 5.x"), _T("Star Sail.x"),
_T("Heli.x"), };
TCHAR* g_strShipNames[] = { _T("Concept Plane"), _T("Green Machine"), _T("Purple Prowler"),
_T("Drone Clone"), _T("Canyon Fighter"), _T("Roundabout"),
_T("Tie-X7"), _T("Gunner"), _T("Star Sail"),
_T("Helicopter"), };
//-----------------------------------------------------------------------------
// Name: struct DisplayObject
// Desc: A game object that goes in the display list
//-----------------------------------------------------------------------------
struct DisplayObject
{
DisplayObject* pNext; // Link to next object
DisplayObject* pPrev; // Link to previous object
DWORD dwType; // Type of object
BOOL bVisible; // Whether the object is visible
D3DXVECTOR3 vPos; // Position
D3DXVECTOR3 vVel; // Velocity
FLOAT fSize;
// Constructor
DisplayObject( DWORD type, D3DVECTOR p, D3DVECTOR v );
};
//-----------------------------------------------------------------------------
// Derived classes for displayable game objects
//-----------------------------------------------------------------------------
struct C3DSprite : public DisplayObject
{
DWORD dwFramesPerLine; // How anim frames are packed in bitmap
FLOAT frame; // Current animation frame
FLOAT fMaxFrame; // Max animation frame value
FLOAT delay; // Frame/second
DWORD dwColor;
DWORD dwTextureOffsetX; // Pixel offsets into the game texture
DWORD dwTextureOffsetY;
DWORD dwTextureWidth; // Width and height in pixels
DWORD dwTextureHeight;
C3DSprite( DWORD type, D3DVECTOR p, D3DVECTOR v );
};
class CDonut : public C3DSprite
{
public:
CDonut( D3DVECTOR p, D3DVECTOR v );
};
class CPyramid : public C3DSprite
{
public:
CPyramid( D3DVECTOR p, D3DVECTOR v );
};
class CSphere : public C3DSprite
{
public:
CSphere( D3DVECTOR p, D3DVECTOR v );
};
class CCube : public C3DSprite
{
public:
CCube( D3DVECTOR p, D3DVECTOR v );
};
class CCloud : public C3DSprite
{
public:
CCloud( D3DVECTOR p, D3DVECTOR v );
};
class CBullet : public C3DSprite
{
public:
CBullet( D3DVECTOR p, D3DVECTOR v, DWORD dwType );
};
class CShip : public DisplayObject
{
public:
FLOAT fRoll;
FLOAT fAngle;
BOOL bExploded;
FLOAT fShowDelay;
public:
CShip( D3DVECTOR p );
};
//-----------------------------------------------------------------------------
// Custom Direct3D vertex types
//-----------------------------------------------------------------------------
struct SCREENVERTEX
{
D3DXVECTOR4 p;
DWORD color;
};
struct SPRITEVERTEX
{
D3DXVECTOR3 p;
DWORD color;
FLOAT tu, tv;
};
struct MODELVERTEX
{
D3DXVECTOR3 p;
D3DXVECTOR3 n;
FLOAT tu, tv;
};
#define D3DFVF_SCREENVERTEX (D3DFVF_XYZRHW|D3DFVF_DIFFUSE)
#define D3DFVF_SPRITEVERTEX (D3DFVF_XYZ|D3DFVF_DIFFUSE|D3DFVF_TEX1)
#define D3DFVF_MODELVERTEX (D3DFVF_XYZ|D3DFVF_NORMAL|D3DFVF_TEX1)
//-----------------------------------------------------------------------------
// App defined structures
//-----------------------------------------------------------------------------
// DirectInput action mapper reports events only when buttons/axis change
// so we need to remember the present state of relevant axis/buttons for
// each DirectInput device. The CInputDeviceManager will store a
// pointer for each device that points to this struct
struct InputDeviceState
{
FLOAT fAxisMoveUD;
BOOL bButtonForwardThrust;
BOOL bButtonReverseThrust;
FLOAT fAxisRotateLR;
BOOL bButtonRotateLeft;
BOOL bButtonRotateRight;
BOOL bButtonFireWeapons;
// Menu input variables
FLOAT fAxisMenuUD;
};
// Struct to store the current input state
struct UserInput
{
FLOAT fAxisMoveUD;
FLOAT fAxisRotateLR;
BOOL bButtonFireWeapons;
BOOL bButtonEnableShield;
// One-shot variables
BOOL bDoChangeView;
// Menu input variables
BOOL bDoMenuUp;
BOOL bDoMenuDown;
BOOL bDoMenuSelect;
BOOL bDoMenuQuit;
};
//-----------------------------------------------------------------------------
// Game actions (using DInput semantic mapper). The definitions here are kind
// of the whole point of this sample. The game uses these actions to map
// physical input like, "the user pressed the 'W' key", to a more useable
// constant for the game, like "if( dwInput == INPUT_CHANGEWEAPONS )...".
//-----------------------------------------------------------------------------
// Input semantics used by this game
enum INPUT_SEMANTICS
{
// Gameplay semantics
INPUT_AXIS_LR=1, INPUT_AXIS_UD,
INPUT_MOUSE_LR, INPUT_MOUSE_UD, INPUT_MOUSE_SHIPTYPE,
INPUT_TURNLEFT, INPUT_TURNRIGHT, INPUT_FORWARDTHRUST,
INPUT_REVERSETHRUST, INPUT_FIREWEAPONS, INPUT_CHANGESHIPTYPE,
INPUT_CHANGEVIEW, INPUT_CHANGEWEAPONS, INPUT_DISPLAYGAMEMENU,
INPUT_QUITGAME, INPUT_START,
// Menu semantics
INPUT_MENU_UD, INPUT_MENU_WHEEL,
INPUT_MENU_UP, INPUT_MENU_DOWN,
INPUT_MENU_SELECT, INPUT_MENU_QUIT,
};
// Game actions used by this game.
DIACTION g_rgGameAction[] =
{
// (C:\Program Files\DirectX\DirectInput\User Maps\*.ini)
// after changing this, otherwise settings won't reset and will be read
// from the out of date ini files
// Device input (joystick, etc.) that is pre-defined by DInput, according
// to genre type. The genre for this app is space simulators.
{ INPUT_AXIS_LR, DIAXIS_SPACESIM_LATERAL, 0, TEXT("Turn"), },
{ INPUT_AXIS_UD, DIAXIS_SPACESIM_MOVE, 0, TEXT("Move"), },
{ INPUT_FIREWEAPONS, DIBUTTON_SPACESIM_FIRE, 0, TEXT("Fire weapons"), },
{ INPUT_CHANGEVIEW, DIBUTTON_SPACESIM_VIEW, 0, TEXT("Change view"), },
{ INPUT_CHANGEWEAPONS, DIBUTTON_SPACESIM_WEAPONS, 0, TEXT("Change weapons"), },
{ INPUT_CHANGESHIPTYPE, DIBUTTON_SPACESIM_LOWER, 0, TEXT("Change ship type"), },
{ INPUT_DISPLAYGAMEMENU, DIBUTTON_SPACESIM_DEVICE, 0, TEXT("Display game menu"), },
{ INPUT_START, DIBUTTON_SPACESIM_MENU, 0, TEXT("Start/pause"), },
// Keyboard input mappings
{ INPUT_TURNLEFT, DIKEYBOARD_LEFT, 0, TEXT("Turn left"), },
{ INPUT_TURNRIGHT, DIKEYBOARD_RIGHT, 0, TEXT("Turn right"), },
{ INPUT_FORWARDTHRUST, DIKEYBOARD_UP, 0, TEXT("Forward thrust"), },
{ INPUT_REVERSETHRUST, DIKEYBOARD_DOWN, 0, TEXT("Reverse thrust"), },
{ INPUT_FIREWEAPONS, DIKEYBOARD_SPACE, 0, TEXT("Fire weapons"), },
{ INPUT_CHANGESHIPTYPE, DIKEYBOARD_A, 0, TEXT("Change ship type"), },
{ INPUT_CHANGEVIEW, DIKEYBOARD_V, 0, TEXT("Change view"), },
{ INPUT_CHANGEWEAPONS, DIKEYBOARD_W, 0, TEXT("Change weapons"), },
{ INPUT_DISPLAYGAMEMENU, DIKEYBOARD_F1, DIA_APPFIXED, TEXT("Display game menu"), },
{ INPUT_START, DIKEYBOARD_PAUSE, 0, TEXT("Start/pause"), },
{ INPUT_QUITGAME, DIKEYBOARD_ESCAPE, DIA_APPFIXED, TEXT("Quit game"), },
// Mouse input mappings
{ INPUT_MOUSE_LR, DIMOUSE_XAXIS, 0, TEXT("Turn"), },
{ INPUT_MOUSE_UD, DIMOUSE_YAXIS, 0, TEXT("Move"), },
{ INPUT_MOUSE_SHIPTYPE, DIMOUSE_WHEEL, 0, TEXT("Change ship type"), },
{ INPUT_FIREWEAPONS, DIMOUSE_BUTTON0, 0, TEXT("Fire weapons"), },
{ INPUT_CHANGEWEAPONS, DIMOUSE_BUTTON1, 0, TEXT("Change weapons"), },
};
// Game actions used by this game.
DIACTION g_rgBrowserAction[] =
{
// (C:\Program Files\DirectX\DirectInput\User Maps\*.ini)
// after changing this, otherwise settings won't reset and will be read
// from the out of date ini files
// Device input (joystick, etc.) that is pre-defined by DInput, according
// to genre type. The genre for this app is space simulators.
{ INPUT_MENU_UD, DIAXIS_BROWSER_MOVE, 0, TEXT("Up/down"), },
{ INPUT_MENU_UP, DIBUTTON_BROWSER_PREVIOUS, 0, TEXT("Up"), },
{ INPUT_MENU_DOWN, DIBUTTON_BROWSER_NEXT, 0, TEXT("Down"), },
{ INPUT_MENU_SELECT, DIBUTTON_BROWSER_SELECT, 0, TEXT("Select"), },
{ INPUT_MENU_QUIT, DIBUTTON_BROWSER_DEVICE, 0, TEXT("Quit menu"), },
// Keyboard input mappings
{ INPUT_MENU_UP, DIKEYBOARD_UP, 0, TEXT("Up"), },
{ INPUT_MENU_DOWN, DIKEYBOARD_DOWN, 0, TEXT("Down"), },
{ INPUT_MENU_SELECT, DIKEYBOARD_SPACE, 0, TEXT("Select"), },
{ INPUT_MENU_SELECT, DIKEYBOARD_RETURN, 0, TEXT("Select"), },
{ INPUT_MENU_SELECT, DIKEYBOARD_NUMPADENTER, 0, TEXT("Select"), },
{ INPUT_MENU_QUIT, DIKEYBOARD_ESCAPE, 0, TEXT("Quit menu"), },
// Mouse input mappings
{ INPUT_MENU_WHEEL, DIMOUSE_WHEEL, 0, TEXT("Up/down"), },
{ INPUT_MENU_SELECT, DIMOUSE_BUTTON0, 0, TEXT("Select"), },
};
// Number of actions
#define NUMBER_OF_GAMEACTIONS (sizeof(g_rgGameAction)/sizeof(DIACTION))
#define NUMBER_OF_BROWSERACTIONS (sizeof(g_rgBrowserAction)/sizeof(DIACTION))
//-----------------------------------------------------------------------------
// Inline helper functions
//-----------------------------------------------------------------------------
// Simple function to define "hilliness" for terrain
inline FLOAT HeightField( FLOAT x, FLOAT z )
{
return (cosf(x/2.0f+0.2f)*cosf(z/1.5f-0.2f)+1.0f) - 2.0f;
}
// Simple function for generating random numbers
inline FLOAT rnd( FLOAT low, FLOAT high )
{
return low + ( high - low ) * ( (FLOAT)rand() ) / RAND_MAX;
}
FLOAT rnd( FLOAT low=-1.0f, FLOAT high=1.0f );
// Convenient macros for playing sounds
inline VOID PlaySound( CMusicSegment* pSound )
{
if( pSound ) pSound->Play( DMUS_SEGF_SECONDARY );
}
inline VOID StopSound( CMusicSegment* pSound )
{
if( pSound ) pSound->Stop();
}
//-----------------------------------------------------------------------------
// Function prototypes
//-----------------------------------------------------------------------------
LRESULT CALLBACK StaticMsgProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam );
//-----------------------------------------------------------------------------
// Name: class CMyApplication
// Desc: Application class.
//-----------------------------------------------------------------------------
class CMyApplication
{
public:
HRESULT Create( HINSTANCE hInstance );
INT Run();
LRESULT MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam );
CMyApplication();
HRESULT InputAddDeviceCB( CInputDeviceManager::DeviceInfo* pDeviceInfo, const DIDEVICEINSTANCE* pdidi );
static HRESULT CALLBACK StaticInputAddDeviceCB( CInputDeviceManager::DeviceInfo* pDeviceInfo, const DIDEVICEINSTANCE* pdidi, LPVOID pParam );
BOOL ConfigureInputDevicesCB( IUnknown* pUnknown );
static BOOL CALLBACK StaticConfigureInputDevicesCB( IUnknown* pUnknown, VOID* pUserData );
protected:
HRESULT OneTimeSceneInit( HWND hWnd );
HRESULT FrameMove();
HRESULT RenderFrame();
VOID FinalCleanup();
// Sound functions
HRESULT CreateSoundObjects( HWND hWnd );
VOID DestroySoundObjects();
// Input functions
HRESULT CreateInputObjects( HWND hWnd );
VOID DestroyInputObjects();
void UpdateInput( UserInput* pUserInput );
// Display functions
HRESULT CreateDisplayObjects( HWND hWnd );
HRESULT RestoreDisplayObjects();
HRESULT InvalidateDisplayObjects();
HRESULT DestroyDisplayObjects();
HRESULT SwitchDisplayModes( BOOL bFullScreen, DWORD dwWidth, DWORD dwHeight );
// Menu functions
VOID ConstructMenus();
VOID DestroyMenus();
VOID UpdateMenus();
// Rendering functions
VOID UpdateDisplayList();
VOID DrawDisplayList();
VOID ShowFrame();
VOID DarkenScene( FLOAT fAmount );
VOID RenderFieryText( CD3DFont* pFont, TCHAR* strText );
// Misc game functions
VOID DisplayLevelIntroScreen( DWORD dwLevel );
VOID AdvanceLevel();
BOOL IsDisplayListEmpty();
VOID AddToList( DisplayObject* pObject );
VOID DeleteFromList( DisplayObject* pObject );
VOID CheckForHits();
HRESULT LoadTerrainModel();
HRESULT LoadShipModel();
HRESULT SwitchModel();
// Error handling
VOID CleanupAndDisplayError( DWORD dwError );
protected:
TCHAR* m_strAppName;
HWND m_hWndMain; // Main window
DWORD m_dwScreenWidth; // Dimensions for fullscreen modes
DWORD m_dwScreenHeight;
D3DDISPLAYMODE m_DesktopMode;
D3DFORMAT m_d3dfmtFullscreen; // Pixel format for fullscreen modes
D3DFORMAT m_d3dfmtTexture; // Pixel format for textures
BOOL m_bFullScreen; // Whether app is fullscreen (or windowed)
BOOL m_bIsActive; // Whether app is active
BOOL m_bDisplayReady; // Whether display class is initialized
BOOL m_bMouseVisible; // Whether mouse is visible
HBITMAP m_hSplashBitmap; // Bitmap for splash screen
DWORD m_dwAppState; // Current state the app is in
DWORD m_dwLevel; // Current game level
DWORD m_dwScore; // Current game score
// Player view mode
#define NUMVIEWMODES 3
CD3DCamera m_Camera; // Camera used for 3D scene
DWORD m_dwViewMode; // Which view mode is being used
FLOAT m_fViewTransition; // Amount used to transittion views
BOOL m_bAnimatingViewChange; // Whether view is transitioning
BOOL m_bFirstPersonView; // Whether view is first-person
// Bullet mode
FLOAT m_fBulletRechargeTime; // Recharge time for firing bullets
DWORD m_dwBulletType; // Current bullet type
// Display list and player ship
DisplayObject* m_pDisplayList; // Global display list
CShip* m_pShip; // Player's display object
// DirectDraw/Direct3D objects
LPDIRECT3DDEVICE8 m_pd3dDevice; // Class to handle D3D device
D3DPRESENT_PARAMETERS m_d3dpp;
LPDIRECT3DSURFACE8 m_pConfigSurface; // Surface for config'ing DInput devices
LPDIRECT3DVERTEXBUFFER8 m_pViewportVB;
LPDIRECT3DVERTEXBUFFER8 m_pSpriteVB;
// Support for the ship model
CD3DMesh* m_pShipFileObject; // Geometry model of player's ship
DWORD m_dwNumShipTypes;
DWORD m_dwCurrentShipType;
// DirectMusic objects
CMusicManager* m_pMusicManager; // Class to manage DMusic objects
CMusicSegment* m_pBeginLevelSound; // Sounds for the app
CMusicSegment* m_pEngineIdleSound;
CMusicSegment* m_pEngineRevSound;
CMusicSegment* m_pShieldBuzzSound;
CMusicSegment* m_pShipExplodeSound;
CMusicSegment* m_pFireBulletSound;
CMusicSegment* m_pShipBounceSound;
CMusicSegment* m_pDonutExplodeSound;
CMusicSegment* m_pPyramidExplodeSound;
CMusicSegment* m_pCubeExplodeSound;
CMusicSegment* m_pSphereExplodeSound;
// Game objects
LPDIRECT3DTEXTURE8 m_pGameTexture1; // Texture with game object animations
LPDIRECT3DTEXTURE8 m_pGameTexture2; // Texture with game object animations
CD3DMesh* m_pTerrain; // Geometry model of terrain
CD3DFont* m_pGameFont; // Font for displaying score, etc.
CD3DFont* m_pMenuFont; // Font for displaying in-game menus
// Menu objects
CMenuItem* m_pMainMenu; // Menu class for in-game menus
CMenuItem* m_pQuitMenu;
CMenuItem* m_pCurrentMenu;
// DirectInput objects
CInputDeviceManager* m_pInputDeviceManager; // Class for managing DInput devices
UserInput m_UserInput; // Struct for storing user input
DIACTIONFORMAT m_diafGame; // Action format for game play
DIACTIONFORMAT m_diafBrowser; // Action format for menu navigation
BOOL m_bPaused;
};
#endif

Binary file not shown.

After

Width:  |  Height:  |  Size: 766 B

View File

@@ -0,0 +1,113 @@
//Microsoft Developer Studio generated resource script.
//
#include "resource.h"
#define APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 2 resource.
//
#define APSTUDIO_HIDDEN_SYMBOLS
#include "windows.h"
#undef APSTUDIO_HIDDEN_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
#undef APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
// English (U.S.) resources
#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
#ifdef _WIN32
LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
#pragma code_page(1252)
#endif //_WIN32
/////////////////////////////////////////////////////////////////////////////
//
// Icon
//
// Icon with lowest ID value placed first to ensure application icon
// remains consistent on all systems.
DONUTS_ICON ICON DISCARDABLE "donuts.ico"
/////////////////////////////////////////////////////////////////////////////
//
// Bitmap
//
SPLASH BITMAP MOVEABLE PURE "SPLASH.BMP"
DONUTS8 BITMAP MOVEABLE PURE "donuts.bmp"
/////////////////////////////////////////////////////////////////////////////
//
// WAV
//
BEGINLEVEL WAV MOVEABLE PURE "level.wav"
ENGINEIDLE WAV MOVEABLE PURE "hum.wav"
ENGINEREV WAV MOVEABLE PURE "rev.wav"
SKIDTOSTOP WAV MOVEABLE PURE "skid.wav"
SHIELDBUZZ WAV MOVEABLE PURE "shield.wav"
GUNFIRE WAV MOVEABLE PURE "gunfire.wav"
SHIPBOUNCE WAV MOVEABLE PURE "bounce.wav"
SHIPEXPLODE WAV MOVEABLE PURE "bangbang.wav"
DONUTEXPLODE WAV MOVEABLE PURE "d_bang.wav"
PYRAMIDEXPLODE WAV MOVEABLE PURE "p_bang.wav"
CUBEEXPLODE WAV MOVEABLE PURE "c_bang.wav"
SPHEREEXPLODE WAV MOVEABLE PURE "s_bang.wav"
#ifdef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// TEXTINCLUDE
//
1 TEXTINCLUDE DISCARDABLE
BEGIN
END
2 TEXTINCLUDE DISCARDABLE
BEGIN
"#define APSTUDIO_HIDDEN_SYMBOLS\r\n"
"#include ""windows.h""\r\n"
"#undef APSTUDIO_HIDDEN_SYMBOLS\r\n"
"\0"
END
3 TEXTINCLUDE DISCARDABLE
BEGIN
"\r\n"
"\0"
END
#endif // APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// Accelerator
//
IDR_MAIN_ACCEL ACCELERATORS DISCARDABLE
BEGIN
VK_RETURN, IDM_TOGGLEFULLSCREEN, VIRTKEY, ALT, NOINVERT
END
#endif // English (U.S.) resources
/////////////////////////////////////////////////////////////////////////////
#ifndef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 3 resource.
//
/////////////////////////////////////////////////////////////////////////////
#endif // not APSTUDIO_INVOKED

View File

@@ -0,0 +1,228 @@
# Microsoft Developer Studio Project File - Name="Donuts3D" - Package Owner=<4>
# Microsoft Developer Studio Generated Build File, Format Version 6.00
# ** DO NOT EDIT **
# TARGTYPE "Win32 (x86) Application" 0x0101
CFG=Donuts3D - Win32 Debug
!MESSAGE This is not a valid makefile. To build this project using NMAKE,
!MESSAGE use the Export Makefile command and run
!MESSAGE
!MESSAGE NMAKE /f "donuts3d.mak".
!MESSAGE
!MESSAGE You can specify a configuration when running NMAKE
!MESSAGE by defining the macro CFG on the command line. For example:
!MESSAGE
!MESSAGE NMAKE /f "donuts3d.mak" CFG="Donuts3D - Win32 Debug"
!MESSAGE
!MESSAGE Possible choices for configuration are:
!MESSAGE
!MESSAGE "Donuts3D - Win32 Release" (based on "Win32 (x86) Application")
!MESSAGE "Donuts3D - Win32 Debug" (based on "Win32 (x86) Application")
!MESSAGE
# Begin Project
# PROP AllowPerConfigDependencies 0
# PROP Scc_ProjName ""
# PROP Scc_LocalPath ""
CPP=cl.exe
MTL=midl.exe
RSC=rc.exe
!IF "$(CFG)" == "Donuts3D - Win32 Release"
# PROP BASE Use_MFC 0
# PROP BASE Use_Debug_Libraries 0
# PROP BASE Output_Dir "Release"
# PROP BASE Intermediate_Dir "Release"
# PROP BASE Target_Dir ""
# PROP Use_MFC 0
# PROP Use_Debug_Libraries 0
# PROP Output_Dir "Release"
# PROP Intermediate_Dir "Release"
# PROP Ignore_Export_Lib 0
# PROP Target_Dir ""
# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /YX /FD /c
# ADD CPP /nologo /W3 /GX /O2 /I "..\..\common\include" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /YX /FD /c
# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32
# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32
# ADD BASE RSC /l 0x409 /d "NDEBUG"
# ADD RSC /l 0x409 /d "NDEBUG"
BSC32=bscmake.exe
# ADD BASE BSC32 /nologo
# ADD BSC32 /nologo
LINK32=link.exe
# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /machine:I386
# ADD LINK32 d3dx8.lib d3d8.lib d3dxof.lib dxguid.lib dinput8.lib dsound.lib winspool.lib dxerr8.lib ole32.lib winmm.lib kernel32.lib user32.lib gdi32.lib comdlg32.lib advapi32.lib shell32.lib /nologo /subsystem:windows /machine:I386 /stack:0x1f4000,0x1f4000
!ELSEIF "$(CFG)" == "Donuts3D - Win32 Debug"
# PROP BASE Use_MFC 0
# PROP BASE Use_Debug_Libraries 1
# PROP BASE Output_Dir "Debug"
# PROP BASE Intermediate_Dir "Debug"
# PROP BASE Target_Dir ""
# PROP Use_MFC 0
# PROP Use_Debug_Libraries 1
# PROP Output_Dir "Debug"
# PROP Intermediate_Dir "Debug"
# PROP Ignore_Export_Lib 0
# PROP Target_Dir ""
# ADD BASE CPP /nologo /W3 /Gm /GX /Zi /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /YX /FD /c
# ADD CPP /nologo /W3 /Gm /GX /Zi /Od /I "..\..\common\include" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /FD /c
# SUBTRACT CPP /YX
# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32
# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32
# ADD BASE RSC /l 0x409 /d "_DEBUG"
# ADD RSC /l 0x409 /d "_DEBUG"
BSC32=bscmake.exe
# ADD BASE BSC32 /nologo
# ADD BSC32 /nologo
LINK32=link.exe
# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /debug /machine:I386 /pdbtype:sept
# ADD LINK32 d3dx8dt.lib d3d8.lib d3dxof.lib dxguid.lib dinput8.lib dsound.lib winspool.lib dxerr8.lib ole32.lib winmm.lib kernel32.lib user32.lib gdi32.lib comdlg32.lib advapi32.lib shell32.lib /nologo /subsystem:windows /debug /machine:I386 /pdbtype:sept /stack:0x1f4000,0x1f4000
!ENDIF
# Begin Target
# Name "Donuts3D - Win32 Release"
# Name "Donuts3D - Win32 Debug"
# Begin Group "Resource Files"
# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"
# Begin Source File
SOURCE=.\bangbang.wav
# End Source File
# Begin Source File
SOURCE=.\bounce.wav
# End Source File
# Begin Source File
SOURCE=.\c_bang.wav
# End Source File
# Begin Source File
SOURCE=.\d_bang.wav
# End Source File
# Begin Source File
SOURCE=.\donuts.bmp
# End Source File
# Begin Source File
SOURCE=.\donuts.ico
# End Source File
# Begin Source File
SOURCE=.\donuts.rc
# End Source File
# Begin Source File
SOURCE=.\gunfire.wav
# End Source File
# Begin Source File
SOURCE=.\hum.wav
# End Source File
# Begin Source File
SOURCE=.\level.wav
# End Source File
# Begin Source File
SOURCE=.\p_bang.wav
# End Source File
# Begin Source File
SOURCE=.\resource.h
# End Source File
# Begin Source File
SOURCE=.\rev.wav
# End Source File
# Begin Source File
SOURCE=.\s_bang.wav
# End Source File
# Begin Source File
SOURCE=.\shield.wav
# End Source File
# Begin Source File
SOURCE=.\skid.wav
# End Source File
# Begin Source File
SOURCE=.\splash.bmp
# End Source File
# End Group
# Begin Group "Common"
# PROP Default_Filter ""
# Begin Source File
SOURCE=..\..\common\src\d3dfile.cpp
# End Source File
# Begin Source File
SOURCE=..\..\common\include\d3dfile.h
# End Source File
# Begin Source File
SOURCE=..\..\common\src\d3dfont.cpp
# End Source File
# Begin Source File
SOURCE=..\..\common\include\d3dfont.h
# End Source File
# Begin Source File
SOURCE=..\..\common\src\d3dutil.cpp
# End Source File
# Begin Source File
SOURCE=..\..\common\src\diutil.cpp
# End Source File
# Begin Source File
SOURCE=..\..\common\include\diutil.h
# End Source File
# Begin Source File
SOURCE=..\..\common\src\dmutil.cpp
# End Source File
# Begin Source File
SOURCE=..\..\common\include\dmutil.h
# End Source File
# Begin Source File
SOURCE=..\..\common\src\dxutil.cpp
# End Source File
# Begin Source File
SOURCE=..\..\common\include\dxutil.h
# End Source File
# End Group
# Begin Source File
SOURCE=.\donuts.cpp
# End Source File
# Begin Source File
SOURCE=.\donuts.h
# End Source File
# Begin Source File
SOURCE=.\gamemenu.cpp
# End Source File
# Begin Source File
SOURCE=.\gamemenu.h
# End Source File
# End Target
# End Project

View File

@@ -0,0 +1,29 @@
Microsoft Developer Studio Workspace File, Format Version 6.00
# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE!
###############################################################################
Project: "Donuts3D"=.\donuts3d.dsp - Package Owner=<4>
Package=<5>
{{{
}}}
Package=<4>
{{{
}}}
###############################################################################
Global:
Package=<5>
{{{
}}}
Package=<3>
{{{
}}}
###############################################################################

View File

@@ -0,0 +1,270 @@
# Microsoft Developer Studio Generated NMAKE File, Based on donuts3d.dsp
!IF "$(CFG)" == ""
CFG=Donuts3D - Win32 Debug
!MESSAGE No configuration specified. Defaulting to Donuts3D - Win32 Debug.
!ENDIF
!IF "$(CFG)" != "Donuts3D - Win32 Release" && "$(CFG)" != "Donuts3D - Win32 Debug"
!MESSAGE Invalid configuration "$(CFG)" specified.
!MESSAGE You can specify a configuration when running NMAKE
!MESSAGE by defining the macro CFG on the command line. For example:
!MESSAGE
!MESSAGE NMAKE /f "donuts3d.mak" CFG="Donuts3D - Win32 Debug"
!MESSAGE
!MESSAGE Possible choices for configuration are:
!MESSAGE
!MESSAGE "Donuts3D - Win32 Release" (based on "Win32 (x86) Application")
!MESSAGE "Donuts3D - Win32 Debug" (based on "Win32 (x86) Application")
!MESSAGE
!ERROR An invalid configuration is specified.
!ENDIF
!IF "$(OS)" == "Windows_NT"
NULL=
!ELSE
NULL=nul
!ENDIF
!IF "$(CFG)" == "Donuts3D - Win32 Release"
OUTDIR=.\Release
INTDIR=.\Release
# Begin Custom Macros
OutDir=.\Release
# End Custom Macros
ALL : "$(OUTDIR)\donuts3d.exe"
CLEAN :
-@erase "$(INTDIR)\d3dfile.obj"
-@erase "$(INTDIR)\d3dfont.obj"
-@erase "$(INTDIR)\d3dutil.obj"
-@erase "$(INTDIR)\diutil.obj"
-@erase "$(INTDIR)\dmutil.obj"
-@erase "$(INTDIR)\donuts.obj"
-@erase "$(INTDIR)\donuts.res"
-@erase "$(INTDIR)\dxutil.obj"
-@erase "$(INTDIR)\gamemenu.obj"
-@erase "$(INTDIR)\vc60.idb"
-@erase "$(OUTDIR)\donuts3d.exe"
"$(OUTDIR)" :
if not exist "$(OUTDIR)/$(NULL)" mkdir "$(OUTDIR)"
CPP=cl.exe
CPP_PROJ=/nologo /ML /W3 /GX /O2 /I "..\..\common\include" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /Fp"$(INTDIR)\donuts3d.pch" /YX /Fo"$(INTDIR)\\" /Fd"$(INTDIR)\\" /FD /c
.c{$(INTDIR)}.obj::
$(CPP) @<<
$(CPP_PROJ) $<
<<
.cpp{$(INTDIR)}.obj::
$(CPP) @<<
$(CPP_PROJ) $<
<<
.cxx{$(INTDIR)}.obj::
$(CPP) @<<
$(CPP_PROJ) $<
<<
.c{$(INTDIR)}.sbr::
$(CPP) @<<
$(CPP_PROJ) $<
<<
.cpp{$(INTDIR)}.sbr::
$(CPP) @<<
$(CPP_PROJ) $<
<<
.cxx{$(INTDIR)}.sbr::
$(CPP) @<<
$(CPP_PROJ) $<
<<
MTL=midl.exe
MTL_PROJ=/nologo /D "NDEBUG" /mktyplib203 /win32
RSC=rc.exe
RSC_PROJ=/l 0x409 /fo"$(INTDIR)\donuts.res" /d "NDEBUG"
BSC32=bscmake.exe
BSC32_FLAGS=/nologo /o"$(OUTDIR)\donuts3d.bsc"
BSC32_SBRS= \
LINK32=link.exe
LINK32_FLAGS=d3dx8.lib d3d8.lib d3dxof.lib dxguid.lib dinput8.lib dsound.lib winspool.lib dxerr8.lib ole32.lib winmm.lib kernel32.lib user32.lib gdi32.lib comdlg32.lib advapi32.lib shell32.lib /nologo /subsystem:windows /incremental:no /pdb:"$(OUTDIR)\donuts3d.pdb" /machine:I386 /out:"$(OUTDIR)\donuts3d.exe"
LINK32_OBJS= \
"$(INTDIR)\d3dfile.obj" \
"$(INTDIR)\d3dfont.obj" \
"$(INTDIR)\d3dutil.obj" \
"$(INTDIR)\diutil.obj" \
"$(INTDIR)\dmutil.obj" \
"$(INTDIR)\dxutil.obj" \
"$(INTDIR)\donuts.obj" \
"$(INTDIR)\gamemenu.obj" \
"$(INTDIR)\donuts.res"
"$(OUTDIR)\donuts3d.exe" : "$(OUTDIR)" $(DEF_FILE) $(LINK32_OBJS)
$(LINK32) @<<
$(LINK32_FLAGS) $(LINK32_OBJS)
<<
!ELSEIF "$(CFG)" == "Donuts3D - Win32 Debug"
OUTDIR=.\Debug
INTDIR=.\Debug
# Begin Custom Macros
OutDir=.\Debug
# End Custom Macros
ALL : "$(OUTDIR)\donuts3d.exe"
CLEAN :
-@erase "$(INTDIR)\d3dfile.obj"
-@erase "$(INTDIR)\d3dfont.obj"
-@erase "$(INTDIR)\d3dutil.obj"
-@erase "$(INTDIR)\diutil.obj"
-@erase "$(INTDIR)\dmutil.obj"
-@erase "$(INTDIR)\donuts.obj"
-@erase "$(INTDIR)\donuts.res"
-@erase "$(INTDIR)\dxutil.obj"
-@erase "$(INTDIR)\gamemenu.obj"
-@erase "$(INTDIR)\vc60.idb"
-@erase "$(INTDIR)\vc60.pdb"
-@erase "$(OUTDIR)\donuts3d.exe"
-@erase "$(OUTDIR)\donuts3d.ilk"
-@erase "$(OUTDIR)\donuts3d.pdb"
"$(OUTDIR)" :
if not exist "$(OUTDIR)/$(NULL)" mkdir "$(OUTDIR)"
CPP=cl.exe
CPP_PROJ=/nologo /MLd /W3 /Gm /GX /Zi /Od /I "..\..\common\include" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /Fo"$(INTDIR)\\" /Fd"$(INTDIR)\\" /FD /c
.c{$(INTDIR)}.obj::
$(CPP) @<<
$(CPP_PROJ) $<
<<
.cpp{$(INTDIR)}.obj::
$(CPP) @<<
$(CPP_PROJ) $<
<<
.cxx{$(INTDIR)}.obj::
$(CPP) @<<
$(CPP_PROJ) $<
<<
.c{$(INTDIR)}.sbr::
$(CPP) @<<
$(CPP_PROJ) $<
<<
.cpp{$(INTDIR)}.sbr::
$(CPP) @<<
$(CPP_PROJ) $<
<<
.cxx{$(INTDIR)}.sbr::
$(CPP) @<<
$(CPP_PROJ) $<
<<
MTL=midl.exe
MTL_PROJ=/nologo /D "_DEBUG" /mktyplib203 /win32
RSC=rc.exe
RSC_PROJ=/l 0x409 /fo"$(INTDIR)\donuts.res" /d "_DEBUG"
BSC32=bscmake.exe
BSC32_FLAGS=/nologo /o"$(OUTDIR)\donuts3d.bsc"
BSC32_SBRS= \
LINK32=link.exe
LINK32_FLAGS=d3dx8dt.lib d3d8.lib d3dxof.lib dxguid.lib dinput8.lib dsound.lib winspool.lib dxerr8.lib ole32.lib winmm.lib kernel32.lib user32.lib gdi32.lib comdlg32.lib advapi32.lib shell32.lib /nologo /subsystem:windows /incremental:yes /pdb:"$(OUTDIR)\donuts3d.pdb" /debug /machine:I386 /out:"$(OUTDIR)\donuts3d.exe" /pdbtype:sept
LINK32_OBJS= \
"$(INTDIR)\d3dfile.obj" \
"$(INTDIR)\d3dfont.obj" \
"$(INTDIR)\d3dutil.obj" \
"$(INTDIR)\diutil.obj" \
"$(INTDIR)\dmutil.obj" \
"$(INTDIR)\dxutil.obj" \
"$(INTDIR)\donuts.obj" \
"$(INTDIR)\gamemenu.obj" \
"$(INTDIR)\donuts.res"
"$(OUTDIR)\donuts3d.exe" : "$(OUTDIR)" $(DEF_FILE) $(LINK32_OBJS)
$(LINK32) @<<
$(LINK32_FLAGS) $(LINK32_OBJS)
<<
!ENDIF
!IF "$(NO_EXTERNAL_DEPS)" != "1"
!IF EXISTS("donuts3d.dep")
!INCLUDE "donuts3d.dep"
!ELSE
!MESSAGE Warning: cannot find "donuts3d.dep"
!ENDIF
!ENDIF
!IF "$(CFG)" == "Donuts3D - Win32 Release" || "$(CFG)" == "Donuts3D - Win32 Debug"
SOURCE=.\donuts.rc
"$(INTDIR)\donuts.res" : $(SOURCE) "$(INTDIR)"
$(RSC) $(RSC_PROJ) $(SOURCE)
SOURCE=..\..\common\src\d3dfile.cpp
"$(INTDIR)\d3dfile.obj" : $(SOURCE) "$(INTDIR)"
$(CPP) $(CPP_PROJ) $(SOURCE)
SOURCE=..\..\common\src\d3dfont.cpp
"$(INTDIR)\d3dfont.obj" : $(SOURCE) "$(INTDIR)"
$(CPP) $(CPP_PROJ) $(SOURCE)
SOURCE=..\..\common\src\d3dutil.cpp
"$(INTDIR)\d3dutil.obj" : $(SOURCE) "$(INTDIR)"
$(CPP) $(CPP_PROJ) $(SOURCE)
SOURCE=..\..\common\src\diutil.cpp
"$(INTDIR)\diutil.obj" : $(SOURCE) "$(INTDIR)"
$(CPP) $(CPP_PROJ) $(SOURCE)
SOURCE=..\..\common\src\dmutil.cpp
"$(INTDIR)\dmutil.obj" : $(SOURCE) "$(INTDIR)"
$(CPP) $(CPP_PROJ) $(SOURCE)
SOURCE=..\..\common\src\dxutil.cpp
"$(INTDIR)\dxutil.obj" : $(SOURCE) "$(INTDIR)"
$(CPP) $(CPP_PROJ) $(SOURCE)
SOURCE=.\donuts.cpp
"$(INTDIR)\donuts.obj" : $(SOURCE) "$(INTDIR)"
SOURCE=.\gamemenu.cpp
"$(INTDIR)\gamemenu.obj" : $(SOURCE) "$(INTDIR)"
!ENDIF

View File

@@ -0,0 +1,141 @@
//-----------------------------------------------------------------------------
// File: GameMenu.cpp
//
// Desc: Code for in-game menus
//
// Copyright (C) 1999-2001 Microsoft Corporation. All Rights Reserved.
//-----------------------------------------------------------------------------
#define STRICT
#define D3D_OVERLOADS
#include <D3D8.h>
#include <D3DX8Math.h>
#include <mmsystem.h>
#include "D3DFont.h"
#include "D3DUtil.h"
#include "GameMenu.h"
//-----------------------------------------------------------------------------
// Name:
// Desc:
//-----------------------------------------------------------------------------
CMenuItem::CMenuItem( TCHAR* strNewLabel, DWORD dwNewID )
{
_tcscpy( strLabel, strNewLabel );
dwID = dwNewID;
pParent = NULL;
dwNumChildren = 0L;
dwSelectedMenu = 0L;
}
//-----------------------------------------------------------------------------
// Name:
// Desc:
//-----------------------------------------------------------------------------
CMenuItem::~CMenuItem()
{
while( dwNumChildren )
delete pChild[--dwNumChildren];
}
//-----------------------------------------------------------------------------
// Name:
// Desc:
//-----------------------------------------------------------------------------
CMenuItem* CMenuItem::Add( CMenuItem* pNewChild )
{
pChild[dwNumChildren++] = pNewChild;
pNewChild->pParent = this;
return pNewChild;
}
//-----------------------------------------------------------------------------
// Name: Render()
// Desc:
//-----------------------------------------------------------------------------
HRESULT CMenuItem::Render( LPDIRECT3DDEVICE8 pd3dDevice, CD3DFont* pFont )
{
// Check parameters
if( NULL==pd3dDevice || NULL==pFont )
return E_INVALIDARG;
// Save current matrices
D3DXMATRIX matViewSaved, matProjSaved;
pd3dDevice->GetTransform( D3DTS_VIEW, &matViewSaved );
pd3dDevice->GetTransform( D3DTS_PROJECTION, &matProjSaved );
// Setup new view and proj matrices for head-on viewing
D3DXMATRIX matView, matProj;
D3DXMatrixLookAtLH( &matView, &D3DXVECTOR3(0.0f,0.0f,-30.0f),
&D3DXVECTOR3(0.0f,0.0f,0.0f),
&D3DXVECTOR3(0.0f,1.0f,0.0f) );
D3DXMatrixPerspectiveFovLH( &matProj, D3DX_PI/4, 1.0f, 1.0f, 100.0f );
pd3dDevice->SetTransform( D3DTS_VIEW, &matView );
pd3dDevice->SetTransform( D3DTS_PROJECTION, &matProj );
// Establish colors for selected vs. normal menu items
D3DMATERIAL8 mtrlNormal, mtrlSelected, mtrlTitle;
D3DUtil_InitMaterial( mtrlTitle, 1.0f, 0.0f, 0.0f, 1.0f );
D3DUtil_InitMaterial( mtrlNormal, 1.0f, 1.0f, 1.0f, 0.5f );
D3DUtil_InitMaterial( mtrlSelected, 1.0f, 1.0f, 0.0f, 1.0f );
pd3dDevice->SetRenderState( D3DRS_LIGHTING, TRUE );
pd3dDevice->SetRenderState( D3DRS_AMBIENT, 0xffffffff );
// Translate the menuitem into place
D3DXMATRIX matWorld;
D3DXMatrixScaling( &matWorld, 0.4f, 0.4f, 0.4f );
matWorld._42 = (dwNumChildren*1.0f) + 2.0f;
pd3dDevice->SetTransform( D3DTS_WORLD, &matWorld );
pd3dDevice->SetMaterial( &mtrlTitle );
// Render the menuitem's label
pFont->Render3DText( strLabel, D3DFONT_CENTERED|D3DFONT_TWOSIDED );
// Loop through and render all menuitem lables
for( DWORD i=0; i<dwNumChildren; i++ )
{
D3DXMATRIX matWorld;
D3DXMatrixScaling( &matWorld, 0.3f, 0.3f, 0.3f );
pd3dDevice->SetMaterial( &mtrlNormal );
// Give a different effect for selected items
if( dwSelectedMenu == i )
{
D3DXMATRIX matRotate;
D3DXMatrixRotationY( &matRotate, (D3DX_PI/3)*sinf(timeGetTime()/200.0f) );
D3DXMatrixMultiply( &matWorld, &matWorld, &matRotate );
pd3dDevice->SetMaterial( &mtrlSelected );
}
// Translate the menuitem into place
matWorld._42 = (dwNumChildren*1.0f) - (i*2.0f);
pd3dDevice->SetTransform( D3DTS_WORLD, &matWorld );
// Render the menuitem's label
pFont->Render3DText( pChild[i]->strLabel,
D3DFONT_CENTERED|D3DFONT_TWOSIDED );
}
// Restore matrices
pd3dDevice->SetTransform( D3DTS_VIEW, &matViewSaved );
pd3dDevice->SetTransform( D3DTS_PROJECTION, &matProjSaved );
return S_OK;
}

View File

@@ -0,0 +1,47 @@
//-----------------------------------------------------------------------------
// File: GameMenu.h
//
// Desc: Code for in-game menus
//
// Copyright (C) 1999-2001 Microsoft Corporation. All Rights Reserved.
//-----------------------------------------------------------------------------
#ifndef GAMEMENU_H
#define GAMEMENU_H
//-----------------------------------------------------------------------------
// Name: class CMenuItem
// Desc:
//-----------------------------------------------------------------------------
class CMenuItem
{
public:
TCHAR strLabel[80];
DWORD dwID;
CMenuItem* pParent;
CMenuItem* pChild[10];
DWORD dwNumChildren;
DWORD dwSelectedMenu;
public:
HRESULT Render( LPDIRECT3DDEVICE8 pd3dDevice, CD3DFont* pFont );
CMenuItem* Add( CMenuItem* );
CMenuItem( TCHAR* strLabel, DWORD dwID );
~CMenuItem();
};
#endif

Binary file not shown.

View File

@@ -0,0 +1,18 @@
//{{NO_DEPENDENCIES}}
// Microsoft Developer Studio generated include file.
// Used by donuts.rc
//
#define DONUTS_ICON 101
#define IDR_MAIN_ACCEL 103
#define IDM_TOGGLEFULLSCREEN 40002
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 105
#define _APS_NEXT_COMMAND_VALUE 40015
#define _APS_NEXT_CONTROL_VALUE 1000
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif

View File

@@ -0,0 +1,17 @@
//{{NO_DEPENDENCIES}}
// Microsoft Developer Studio generated include file.
// Used by donuts.rc
//
#define IDR_MAIN_ACCEL 103
#define IDM_TOGGLEFULLSCREEN 40002
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 104
#define _APS_NEXT_COMMAND_VALUE 40003
#define _APS_NEXT_CONTROL_VALUE 1000
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 750 KiB

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 518 B

View File

@@ -0,0 +1,221 @@
//-----------------------------------------------------------------------------
// File: DDutil.cpp
//
// Desc: Routines for loading bitmap and palettes from resources
//
// Copyright (C) 1995-2001 Microsoft Corporation. All Rights Reserved.
//-----------------------------------------------------------------------------
#undef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#include <ddraw.h>
#include "ddutil.h"
//-----------------------------------------------------------------------------
// Name: DDUtil_CopyBitmap()
// Desc: Draw a bitmap into a DirectDrawSurface
//-----------------------------------------------------------------------------
HRESULT DDUtil_CopyBitmap( LPDIRECTDRAWSURFACE pdds, HBITMAP hbm, int x, int y,
int dx, int dy )
{
HDC hdcImage;
HDC hdc;
BITMAP bm;
DDSURFACEDESC ddsd;
HRESULT hr;
if( hbm == NULL || pdds == NULL )
return E_FAIL;
// Make sure this surface is restored.
pdds->Restore();
// Select bitmap into a memoryDC so we can use it.
hdcImage = CreateCompatibleDC(NULL);
if( !hdcImage )
{
OutputDebugString( TEXT("CreateCompatibleDC() failed\n") );
return E_FAIL;
}
SelectObject( hdcImage, hbm );
// Get size of the bitmap
GetObject( hbm, sizeof(bm), &bm ); // get size of bitmap
dx = dx == 0 ? bm.bmWidth : dx; // use the passed size, unless zero
dy = dy == 0 ? bm.bmHeight : dy;
// Gt size of surface.
ddsd.dwSize = sizeof(ddsd);
ddsd.dwFlags = DDSD_HEIGHT | DDSD_WIDTH;
pdds->GetSurfaceDesc(&ddsd);
if( SUCCEEDED( hr = pdds->GetDC(&hdc) ) )
{
StretchBlt( hdc, 0, 0, ddsd.dwWidth, ddsd.dwHeight, hdcImage,
x, y, dx, dy, SRCCOPY);
pdds->ReleaseDC( hdc );
}
DeleteDC( hdcImage );
return hr;
}
//-----------------------------------------------------------------------------
// Name: DDUtil_LoadPalette()
// Desc: Create a DirectDraw palette object from a bitmap resoure
// If the resource does not exist or NULL is passed create a
// default 332 palette.
//-----------------------------------------------------------------------------
LPDIRECTDRAWPALETTE DDUtil_LoadPalette( LPDIRECTDRAW pDD, TCHAR* strBitmap )
{
LPDIRECTDRAWPALETTE pddPalette;
int i;
int n;
HANDLE fh;
HRSRC h;
LPBITMAPINFOHEADER lpbi;
PALETTEENTRY ape[256];
RGBQUAD* prgb;
DWORD dwRead;
// Build a 332 palette as the default.
for( i=0; i<256; i++ )
{
ape[i].peRed = (BYTE)(((i >> 5) & 0x07) * 255 / 7);
ape[i].peGreen = (BYTE)(((i >> 2) & 0x07) * 255 / 7);
ape[i].peBlue = (BYTE)(((i >> 0) & 0x03) * 255 / 3);
ape[i].peFlags = (BYTE)0;
}
// Gt a pointer to the bitmap resource.
if( strBitmap && ( h = FindResource( NULL, strBitmap, RT_BITMAP ) ) )
{
lpbi = (LPBITMAPINFOHEADER)LockResource( LoadResource( NULL, h ) );
if( NULL == lpbi )
OutputDebugString(TEXT("lock resource failed\n"));
prgb = (RGBQUAD*)((BYTE*)lpbi + lpbi->biSize);
if (lpbi == NULL || lpbi->biSize < sizeof(BITMAPINFOHEADER))
n = 0;
else if (lpbi->biBitCount > 8)
n = 0;
else if (lpbi->biClrUsed == 0)
n = 1 << lpbi->biBitCount;
else
n = lpbi->biClrUsed;
// A DIB color table has its colors stored BGR not RGB, so flip them
for(i=0; i<n; i++ )
{
ape[i].peRed = prgb[i].rgbRed;
ape[i].peGreen = prgb[i].rgbGreen;
ape[i].peBlue = prgb[i].rgbBlue;
ape[i].peFlags = 0;
}
}
else if( strBitmap && ( fh = CreateFile( strBitmap, GENERIC_READ,
FILE_SHARE_READ, NULL, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, NULL ) ) != INVALID_HANDLE_VALUE )
{
BITMAPFILEHEADER bf;
BITMAPINFOHEADER bi;
ReadFile( fh, &bf, sizeof(bf), &dwRead, NULL );
ReadFile( fh, &bi, sizeof(bi), &dwRead, NULL );
ReadFile( fh, ape, sizeof(ape), &dwRead, NULL );
CloseHandle( fh );
if( bi.biSize != sizeof(BITMAPINFOHEADER) )
n = 0;
else if( bi.biBitCount > 8 )
n = 0;
else if( bi.biClrUsed == 0 )
n = 1 << bi.biBitCount;
else
n = bi.biClrUsed;
// A DIB color table has its colors stored BGR not RGB so flip them
for(i=0; i<n; i++ )
{
BYTE r = ape[i].peRed;
ape[i].peRed = ape[i].peBlue;
ape[i].peBlue = r;
}
}
pDD->CreatePalette( DDPCAPS_8BIT, ape, &pddPalette, NULL );
return pddPalette;
}
//-----------------------------------------------------------------------------
// Name: DDUtil_ColorMatch()
// Desc: Convert a RGB color to a pysical color. We do this by leting GDI
// SetPixel() do the color matching.
//-----------------------------------------------------------------------------
DWORD DDUtil_ColorMatch( LPDIRECTDRAWSURFACE pdds, COLORREF rgb )
{
DDSURFACEDESC ddsd;
COLORREF rgbT;
HDC hdc;
DWORD dw = CLR_INVALID;
HRESULT hr;
// Wse GDI SetPixel to color match for us
if( rgb != CLR_INVALID && SUCCEEDED( pdds->GetDC(&hdc) ) )
{
rgbT = GetPixel( hdc, 0, 0 ); // Save current pixel value
SetPixel( hdc, 0, 0, rgb ); // Set our value
pdds->ReleaseDC( hdc );
}
// Now lock the surface so we can read back the converted color
ddsd.dwSize = sizeof(ddsd);
while( ( hr = pdds->Lock( NULL, &ddsd, 0, NULL ) ) == DDERR_WASSTILLDRAWING )
{}
if( SUCCEEDED(hr) )
{
dw = *(DWORD *)ddsd.lpSurface; // get DWORD
dw &= (1 << ddsd.ddpfPixelFormat.dwRGBBitCount)-1; // mask it to bpp
pdds->Unlock(NULL);
}
// Now put the color that was there back.
if( rgb != CLR_INVALID && SUCCEEDED( pdds->GetDC(&hdc) ) )
{
SetPixel( hdc, 0, 0, rgbT );
pdds->ReleaseDC( hdc );
}
return dw;
}
//-----------------------------------------------------------------------------
// Name: DDUtil_SetColorKey()
// Desc: Set a color key for a surface, given a RGB. If you pass CLR_INVALID as
// the color key, the pixel in the upper-left corner will be used.
//-----------------------------------------------------------------------------
HRESULT DDUtil_SetColorKey( LPDIRECTDRAWSURFACE pdds, COLORREF rgb )
{
DDCOLORKEY ddck;
ddck.dwColorSpaceLowValue = DDUtil_ColorMatch( pdds, rgb );
ddck.dwColorSpaceHighValue = ddck.dwColorSpaceLowValue;
return pdds->SetColorKey( DDCKEY_SRCBLT, &ddck );
}

View File

@@ -0,0 +1,18 @@
//-----------------------------------------------------------------------------
// File: DDutil.h
//
// Desc: Routines for loading bitmap and palettes from resources
//
// Copyright (C) 1995-2001 Microsoft Corporation. All Rights Reserved.
//-----------------------------------------------------------------------------
#include <tchar.h>
LPDIRECTDRAWPALETTE DDUtil_LoadPalette( LPDIRECTDRAW pDD, TCHAR* strBitmap );
HRESULT DDUtil_CopyBitmap( LPDIRECTDRAWSURFACE pdds, HBITMAP hbm,
int x, int y, int dx, int dy );
DWORD DDUtil_ColorMatch( LPDIRECTDRAWSURFACE pdds, COLORREF rgb );
HRESULT DDUtil_SetColorKey( LPDIRECTDRAWSURFACE pdds, COLORREF rgb );

View File

@@ -0,0 +1,169 @@
//-----------------------------------------------------------------------------
// File: DIUtil.cpp
//
// Desc: Input routines
//
// Copyright (C) 1995-2001 Microsoft Corporation. All Rights Reserved.
//-----------------------------------------------------------------------------
#include "duel.h"
#include "diutil.h"
#include "gameproc.h"
//-----------------------------------------------------------------------------
// Globals
//-----------------------------------------------------------------------------
static LPDIRECTINPUT g_pDI; // DirectInput interface
static LPDIRECTINPUTDEVICE g_pdidKeyboard; // Keyboard device interface
static BOOL g_bKeyboardAcquired; // Whether eyboard is acquired
//-----------------------------------------------------------------------------
// Name: DIUtil_InitInput()
// Desc: Initialize DirectInput objects & devices
//-----------------------------------------------------------------------------
HRESULT DIUtil_InitInput( HWND hWnd )
{
// Create DI object
HINSTANCE hInst;
#ifdef _WIN64
hInst = (HINSTANCE)GetWindowLongPtr( hWnd, GWLP_HINSTANCE );
#else
hInst = (HINSTANCE)GetWindowLong( hWnd, GWL_HINSTANCE );
#endif
if( FAILED( DirectInputCreate( hInst, DIRECTINPUT_VERSION, &g_pDI, NULL ) ) )
{
ShowError(IDS_DINPUT_ERROR_DIC);
return E_FAIL;
}
// Create keyboard device
if( FAILED( g_pDI->CreateDevice( GUID_SysKeyboard, &g_pdidKeyboard, NULL ) ) )
{
ShowError(IDS_DINPUT_ERROR_CD);
return E_FAIL;
}
// Tell DirectInput that we want to receive data in keyboard format
if( FAILED( g_pdidKeyboard->SetDataFormat( &c_dfDIKeyboard) ) )
{
ShowError(IDS_DINPUT_ERROR_DF);
return E_FAIL;
}
// Set cooperative level
if( FAILED( g_pdidKeyboard->SetCooperativeLevel( hWnd,
DISCL_NONEXCLUSIVE | DISCL_FOREGROUND ) ) )
{
ShowError(IDS_DINPUT_ERROR_SP);
return E_FAIL;
}
// try to acquire the keyboard
if( SUCCEEDED( g_pdidKeyboard->Acquire() ) )
g_bKeyboardAcquired = TRUE;
else
g_bKeyboardAcquired = FALSE;
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: DIUtil_ReadKeys()
// Desc: Use DirectInput to read game-play keys
//-----------------------------------------------------------------------------
VOID DIUtil_ReadKeys( DWORD* pdwKeys )
{
BYTE rgbKeybd[256];
DWORD dwKeys = 0L;
HRESULT hr;
hr = g_pdidKeyboard->GetDeviceState( sizeof(rgbKeybd), rgbKeybd );
if( FAILED(hr) )
{
if( hr == DIERR_INPUTLOST )
{
// We lost control of the keyboard, reacquire
if( SUCCEEDED( g_pdidKeyboard->Acquire() ) )
g_bKeyboardAcquired = TRUE;
else
g_bKeyboardAcquired = FALSE;
}
// Failed to read the keyboard, just return
return;
}
// check & update key states
if( rgbKeybd[DIK_NUMPAD5] & 0x80 )
dwKeys |= KEY_STOP;
if( (rgbKeybd[DIK_NUMPAD2] & 0x80) || (rgbKeybd[DIK_DOWN] & 0x80) )
dwKeys |= KEY_DOWN;
if( (rgbKeybd[DIK_NUMPAD4] & 0x80) || (rgbKeybd[DIK_LEFT] & 0x80) )
dwKeys |= KEY_LEFT;
if( (rgbKeybd[DIK_NUMPAD6] & 0x80) || (rgbKeybd[DIK_RIGHT] & 0x80) )
dwKeys |= KEY_RIGHT;
if( (rgbKeybd[DIK_NUMPAD8] & 0x80) || (rgbKeybd[DIK_UP] & 0x80) )
dwKeys |= KEY_UP;
if( rgbKeybd[DIK_SPACE] & 0x80 )
dwKeys |= KEY_FIRE;
// Return the keys
(*pdwKeys) = dwKeys;
}
//-----------------------------------------------------------------------------
// Name: DIUtil_CleanupInput()
// Desc: Cleans up DirectInput objects
//-----------------------------------------------------------------------------
VOID DIUtil_CleanupInput()
{
if(g_bKeyboardAcquired)
{
g_pdidKeyboard->Unacquire();
g_bKeyboardAcquired = FALSE;
}
if( g_pdidKeyboard )
g_pdidKeyboard->Release();
if( g_pDI )
g_pDI->Release();
}
//-----------------------------------------------------------------------------
// Name: DIUtil_ReacquireInputDevices()
// Desc: Reacquires DirectInput devices as needed
//-----------------------------------------------------------------------------
HRESULT DIUtil_ReacquireInputDevices()
{
g_bKeyboardAcquired = FALSE;
if( NULL == g_pdidKeyboard )
return E_FAIL;
g_pdidKeyboard->Acquire();
g_bKeyboardAcquired = TRUE;
return S_OK;
}

View File

@@ -0,0 +1,24 @@
//-----------------------------------------------------------------------------
// File: DIUtil.h
//
// Desc: Input routines
//
// Copyright (C) 1995-2001 Microsoft Corporation. All Rights Reserved.
//-----------------------------------------------------------------------------
#ifndef DIUTIL_H
#define DIUTIL_H
#define DIRECTINPUT_VERSION 0x700
#include <dinput.h>
HRESULT DIUtil_InitInput( HWND hWnd );
VOID DIUtil_ReadKeys( DWORD* pdwKey );
VOID DIUtil_CleanupInput();
HRESULT DIUtil_ReacquireInputDevices();
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,425 @@
//-----------------------------------------------------------------------------
// File: DPUtil.cpp
//
// Desc: Communication routines
//
// Copyright (C) 1995-2001 Microsoft Corporation. All Rights Reserved.
//-----------------------------------------------------------------------------
#include "duel.h"
#include "DPUtil.h"
#include "lobby.h"
//-----------------------------------------------------------------------------
// Globals
//-----------------------------------------------------------------------------
extern GUID g_AppGUID; // Duel's guid
extern DPLCONNECTION* g_pDPLConnection; // Connection settings
extern BOOL g_bUseProtocol; // DirectPlay Protocol messaging
extern BOOL g_bAsyncSupported; // Asynchronous sends supported
DPSESSIONDESC2* g_pdpsd; // Durrent session description
LPDIRECTPLAY4 g_pDP = NULL; // DPlay object pointer
//-----------------------------------------------------------------------------
// Name: CheckCaps()
// Desc: Helper function to check for certain Capabilities
//-----------------------------------------------------------------------------
VOID CheckCaps()
{
HRESULT hr;
DPCAPS dpcaps;
ZeroMemory( &dpcaps, sizeof(DPCAPS) );
dpcaps.dwSize = sizeof(DPCAPS);
if( NULL == g_pDP )
return;
// The caps we are checking do not differ for guaranteed msg
hr = g_pDP->GetCaps( &dpcaps, 0 );
if( FAILED(hr) )
return;
// Determine if Aync messages are supported.
g_bAsyncSupported = (dpcaps.dwFlags & DPCAPS_ASYNCSUPPORTED) != 0;
// Diagnostic traces of caps supported
if( g_bAsyncSupported )
{
TRACE(_T("Capabilities supported: Async %s %s %s\n"),
(dpcaps.dwFlags & DPCAPS_SENDPRIORITYSUPPORTED ? _T("SendPriority") : _T("")),
(dpcaps.dwFlags & DPCAPS_SENDTIMEOUTSUPPORTED ? _T("SendTimeout") : _T("")),
(dpcaps.dwFlags & DPCAPS_ASYNCCANCELSUPPORTED
? _T("AsyncCancel")
: (dpcaps.dwFlags & DPCAPS_ASYNCCANCELALLSUPPORTED
? _T("AsyncCancelAll") : _T("")))
);
}
else
TRACE(_T("CheckCaps - Async not supported\n"));
}
//-----------------------------------------------------------------------------
// Name: DPUtil_FreeDirectPlay()
// Desc: Wrapper for DirectPlay Close API
//-----------------------------------------------------------------------------
HRESULT DPUtil_FreeDirectPlay()
{
if( NULL == g_pDP )
return E_FAIL;
return g_pDP->Close();
}
//-----------------------------------------------------------------------------
// Name: DPUtil_InitDirectPlay()
// Desc: Wrapper for DirectPlay Create API. Retrieves a DirectPlay4/4A
// interface based on the UNICODE flag
//-----------------------------------------------------------------------------
HRESULT DPUtil_InitDirectPlay( VOID* pCon )
{
HRESULT hr;
// Create a DirectPlay4(A) interface
#ifdef UNICODE
hr = CoCreateInstance( CLSID_DirectPlay, NULL, CLSCTX_INPROC_SERVER,
IID_IDirectPlay4, (VOID**)&g_pDP );
#else
hr = CoCreateInstance( CLSID_DirectPlay, NULL, CLSCTX_INPROC_SERVER,
IID_IDirectPlay4A, (VOID**)&g_pDP );
#endif
if( FAILED(hr) )
return hr;
// Initialize w/address
if( pCon )
{
hr = g_pDP->InitializeConnection( pCon, 0 );
if( FAILED(hr) )
{
g_pDP->Release();
g_pDP = NULL;
return hr;
}
}
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: DPUtil_CreatePlayer()
// Desc: Wrapper for DirectPlay CreatePlayer API.
//-----------------------------------------------------------------------------
HRESULT DPUtil_CreatePlayer( DPID* ppidID, TCHAR* strPlayerName, HANDLE hEvent,
VOID* pData, DWORD dwDataSize )
{
if( NULL == g_pDP )
return E_FAIL;
DPNAME dpname;
ZeroMemory( &dpname, sizeof(DPNAME) );
dpname.dwSize = sizeof(DPNAME);
#ifdef UNICODE
dpname.lpszShortName = strPlayerName;
#else
dpname.lpszShortNameA = strPlayerName;
#endif
return g_pDP->CreatePlayer( ppidID, &dpname, hEvent, pData, dwDataSize, 0 );
}
//-----------------------------------------------------------------------------
// Name: DPUtil_CreateSession()
// Desc: Wrapper for DirectPlay CreateSession API.Uses the global application
// guid.
//-----------------------------------------------------------------------------
HRESULT DPUtil_CreateSession( TCHAR* strSessionName )
{
if( NULL == g_pDP )
return DPERR_NOINTERFACE;
DPSESSIONDESC2 dpDesc;
ZeroMemory( &dpDesc, sizeof(dpDesc) );
dpDesc.dwSize = sizeof(dpDesc);
dpDesc.dwFlags = DPSESSION_MIGRATEHOST | DPSESSION_KEEPALIVE;
if( g_bUseProtocol )
dpDesc.dwFlags |= DPSESSION_DIRECTPLAYPROTOCOL;
#ifdef UNICODE
dpDesc.lpszSessionName = strSessionName;
#else
dpDesc.lpszSessionNameA = strSessionName;
#endif
// Set the application guid
dpDesc.guidApplication = g_AppGUID;
HRESULT hr = g_pDP->Open( &dpDesc, DPOPEN_CREATE );
// Check for Async message support
if( SUCCEEDED(hr) )
CheckCaps();
return hr;
}
//-----------------------------------------------------------------------------
// Name: DPUtil_DestroyPlayer()
// Desc: Wrapper for DirectPlay DestroyPlayer API.
//-----------------------------------------------------------------------------
HRESULT DPUtil_DestroyPlayer( DPID pid )
{
if( NULL == g_pDP )
return E_FAIL;
return g_pDP->DestroyPlayer( pid );
}
//-----------------------------------------------------------------------------
// Name: DPUtil_EnumPlayers()
// Desc: Wrapper for DirectPlay API EnumPlayers
//-----------------------------------------------------------------------------
HRESULT DPUtil_EnumPlayers( GUID* pSessionGuid,
LPDPENUMPLAYERSCALLBACK2 pEnumCallback,
VOID* pContext, DWORD dwFlags )
{
if( NULL == g_pDP )
return E_FAIL;
return g_pDP->EnumPlayers( pSessionGuid, pEnumCallback, pContext, dwFlags );
}
//-----------------------------------------------------------------------------
// Name: DPUtil_EnumSessions()
// Desc: Wrapper for DirectPlay EnumSessions API.
//-----------------------------------------------------------------------------
HRESULT DPUtil_EnumSessions( DWORD dwTimeout,
LPDPENUMSESSIONSCALLBACK2 pEnumCallback,
VOID* pContext, DWORD dwFlags )
{
if( NULL == g_pDP )
return E_FAIL;
DPSESSIONDESC2 dpDesc;
ZeroMemory( &dpDesc, sizeof(dpDesc) );
dpDesc.dwSize = sizeof(dpDesc);
dpDesc.guidApplication = g_AppGUID;
return g_pDP->EnumSessions( &dpDesc, dwTimeout, pEnumCallback,
pContext, dwFlags );
}
//-----------------------------------------------------------------------------
// Name: DPUtil_GetPlayerLocalData()
// Desc: Wrapper for DirectPlay GetPlayerData API.
//-----------------------------------------------------------------------------
HRESULT DPUtil_GetPlayerLocalData( DPID pid, VOID* pData, DWORD* pdwDataSize )
{
if( NULL == g_pDP )
return E_FAIL;
HRESULT hr = g_pDP->GetPlayerData( pid, pData, pdwDataSize, DPGET_LOCAL );
if( FAILED(hr) )
TRACE( TEXT("Get Player local data failed for id %d\n"), pid );
return hr;
}
//-----------------------------------------------------------------------------
// Name: DPUtil_GetSessionDesc()
// Desc: Wrapper for DirectPlay GetSessionDesc API.
//-----------------------------------------------------------------------------
HRESULT DPUtil_GetSessionDesc()
{
DWORD dwSize;
HRESULT hr;
// Free old session desc, if any
if( g_pdpsd )
free( g_pdpsd );
g_pdpsd = NULL;
if( NULL == g_pDP )
return E_FAIL;
// First get the size for the session desc
hr = g_pDP->GetSessionDesc( NULL, &dwSize );
if( DPERR_BUFFERTOOSMALL == hr )
{
// Allocate memory for it
g_pdpsd = (DPSESSIONDESC2*)malloc( dwSize );
if( NULL == g_pdpsd )
return E_OUTOFMEMORY;
// Now get the session desc
hr = g_pDP->GetSessionDesc( g_pdpsd, &dwSize );
}
return hr;
}
//-----------------------------------------------------------------------------
// Name: DPUtil_IsDPlayInitialized()
// Desc: Returns TRUE if a DirectPlay interface exists, otherwise FALSE.
//-----------------------------------------------------------------------------
BOOL DPUtil_IsDPlayInitialized()
{
return( g_pDP ? TRUE : FALSE );
}
//-----------------------------------------------------------------------------
// Name: DPUtil_OpenSession()
// Desc: Wrapper for DirectPlay OpenSession API.
//-----------------------------------------------------------------------------
HRESULT DPUtil_OpenSession( GUID* pSessionGUID )
{
if( NULL == g_pDP)
return DPERR_NOINTERFACE;
DPSESSIONDESC2 dpDesc;
ZeroMemory( &dpDesc, sizeof(dpDesc) );
dpDesc.dwSize = sizeof(dpDesc);
if( g_bUseProtocol )
dpDesc.dwFlags = DPSESSION_DIRECTPLAYPROTOCOL;
// Set the session guid
if( pSessionGUID )
dpDesc.guidInstance = (*pSessionGUID);
// Set the application guid
dpDesc.guidApplication = g_AppGUID;
// Open it
HRESULT hr = g_pDP->Open( &dpDesc, DPOPEN_JOIN );
// Check for Async message support
if( SUCCEEDED(hr) )
CheckCaps();
return hr;
}
//-----------------------------------------------------------------------------
// Name: DPUtil_Receive()
// Desc: Wrapper for DirectPlay Receive API
//-----------------------------------------------------------------------------
HRESULT DPUtil_Receive( DPID* pidFrom, DPID* pidTo, DWORD dwFlags, VOID* pData,
DWORD* pdwDataSize )
{
if( NULL == g_pDP )
return E_FAIL;
return g_pDP->Receive( pidFrom, pidTo, dwFlags, pData, pdwDataSize );
}
//-----------------------------------------------------------------------------
// Name: DPUtil_Release()
// Desc: Wrapper for DirectPlay Release API.
//-----------------------------------------------------------------------------
HRESULT DPUtil_Release()
{
if( NULL == g_pDP )
return E_FAIL;
// Free session desc, if any
if( g_pdpsd )
free( g_pdpsd );
g_pdpsd = NULL;
// Free connection settings structure, if any (lobby stuff)
if( g_pDPLConnection )
delete[] g_pDPLConnection;
g_pDPLConnection = NULL;
// Release dplay
HRESULT hr = g_pDP->Release();
g_pDP = NULL;
return hr;
}
//-----------------------------------------------------------------------------
// Name: DPUtil_Send()
// Desc: Wrapper for DirectPlay Send[Ex] API.
//-----------------------------------------------------------------------------
HRESULT DPUtil_Send( DPID idFrom, DPID idTo, DWORD dwFlags, VOID* pData,
DWORD dwDataSize )
{
if( NULL == g_pDP )
return DPERR_NOINTERFACE;
if (dwFlags & DPSEND_ASYNC)
// We don't specify a priority or timeout. Would have to check
// GetCaps() first to see if they were supported
return g_pDP->SendEx( idFrom, idTo, dwFlags, pData, dwDataSize,
0, 0, NULL, NULL );
else
return g_pDP->Send( idFrom, idTo, dwFlags, pData, dwDataSize );
}
//-----------------------------------------------------------------------------
// Name: DPUtil_SetPlayerLocalData()
// Desc: Wrapper for DirectPlay SetPlayerData API
//-----------------------------------------------------------------------------
HRESULT DPUtil_SetPlayerLocalData( DPID pid, VOID* pData, DWORD dwSize )
{
if( NULL == g_pDP )
return E_FAIL;
HRESULT hr = g_pDP->SetPlayerData( pid, pData, dwSize, DPSET_LOCAL );
if( FAILED(hr) )
TRACE( TEXT("Set Player local data failed for id %d\n"), pid );
return hr;
}

View File

@@ -0,0 +1,41 @@
//-----------------------------------------------------------------------------
// File: DPUtil.h
//
// Desc: Communication routines include file
//
// Copyright (C) 1995-2001 Microsoft Corporation. All Rights Reserved.
//-----------------------------------------------------------------------------
#define IDIRECTPLAY2_OR_GREATER
#include <dplay.h>
//-----------------------------------------------------------------------------
// Prototypes
//-----------------------------------------------------------------------------
HRESULT DPUtil_FreeDirectPlay();
HRESULT DPUtil_InitDirectPlay( VOID* pCon );
HRESULT DPUtil_CreatePlayer( DPID* ppidID, LPTSTR pPlayerName, HANDLE hEvent,
VOID* pData, DWORD dwDataSize );
HRESULT DPUtil_CreateSession( TCHAR* strSessionName );
HRESULT DPUtil_DestroyPlayer( DPID pid );
HRESULT DPUtil_EnumPlayers( GUID* pSessionGuid,
LPDPENUMPLAYERSCALLBACK2 lpEnumCallback,
VOID* pContext, DWORD dwFlags );
HRESULT DPUtil_EnumSessions( DWORD dwTimeout,
LPDPENUMSESSIONSCALLBACK2 lpEnumCallback,
VOID* pContext, DWORD dwFlags );
HRESULT DPUtil_GetSessionDesc();
BOOL DPUtil_IsDPlayInitialized();
HRESULT DPUtil_OpenSession( GUID* pSessionGuid );
HRESULT DPUtil_Receive( DPID* pidFrom, DPID* pidTo, DWORD dwFlags, VOID* pData,
DWORD* pdwDataSize );
HRESULT DPUtil_Release();
HRESULT DPUtil_Send( DPID idFrom, DPID idTo, DWORD dwFlags, VOID* pData,
DWORD dwDataSize );
HRESULT DPUtil_SetPlayerLocalData( DPID pid, VOID* pData, DWORD dwSize );
HRESULT DPUtil_GetPlayerLocalData( DPID pid, VOID* pData, DWORD* pdwDataSize );

View File

@@ -0,0 +1,465 @@
//-----------------------------------------------------------------------------
// File: dsutil.cpp
//
// Desc: Routines for dealing with sounds from resources
//
// Copyright (C) 1995-2001 Microsoft Corporation. All Rights Reserved.
//-----------------------------------------------------------------------------
#include <windows.h>
#include <mmsystem.h>
#include <dsound.h>
#include "dsutil.h"
//-----------------------------------------------------------------------------
// Globals
//-----------------------------------------------------------------------------
LPDIRECTSOUND g_pDS = NULL;
//-----------------------------------------------------------------------------
// Name: DSUtil_LoadSoundBuffer()
// Desc:
//-----------------------------------------------------------------------------
LPDIRECTSOUNDBUFFER DSUtil_LoadSoundBuffer( LPDIRECTSOUND pDS, LPCTSTR strName )
{
LPDIRECTSOUNDBUFFER pDSB = NULL;
DSBUFFERDESC dsbd;
BYTE* pbWaveData;
ZeroMemory( &dsbd, sizeof(dsbd) );
dsbd.dwSize = sizeof(dsbd);
dsbd.dwFlags = DSBCAPS_STATIC|DSBCAPS_CTRLPAN|DSBCAPS_CTRLVOLUME|
DSBCAPS_CTRLFREQUENCY|DSBCAPS_CTRLPOSITIONNOTIFY;
if( SUCCEEDED( DSUtil_GetWaveResource( NULL, strName, &dsbd.lpwfxFormat,
&pbWaveData, &dsbd.dwBufferBytes ) ) )
{
if( SUCCEEDED( pDS->CreateSoundBuffer( &dsbd, &pDSB, NULL ) ) )
{
if( FAILED( DSUtil_FillSoundBuffer( pDSB, pbWaveData,
dsbd.dwBufferBytes ) ) )
{
pDSB->Release();
pDSB = NULL;
}
}
else
{
pDSB = NULL;
}
}
return pDSB;
}
//-----------------------------------------------------------------------------
// Name: DSUtil_ReloadSoundBuffer()
// Desc:
//-----------------------------------------------------------------------------
HRESULT DSUtil_ReloadSoundBuffer( LPDIRECTSOUNDBUFFER pDSB, LPCTSTR strName )
{
BYTE* pbWaveData;
DWORD cbWaveSize;
if( FAILED( DSUtil_GetWaveResource( NULL, strName, NULL, &pbWaveData,
&cbWaveSize ) ) )
return E_FAIL;
if( FAILED( pDSB->Restore() ) )
return E_FAIL;
if( FAILED( DSUtil_FillSoundBuffer( pDSB, pbWaveData, cbWaveSize ) ) )
return E_FAIL;
return S_OK;
}
//-----------------------------------------------------------------------------
// Name:
// Desc:
//-----------------------------------------------------------------------------
HRESULT DSUtil_GetWaveResource( HMODULE hModule, LPCTSTR strName,
WAVEFORMATEX** ppWaveHeader, BYTE** ppbWaveData,
DWORD* pcbWaveSize )
{
HRSRC hResInfo;
HGLOBAL hResData;
VOID* pvRes;
if( NULL == ( hResInfo = FindResource( hModule, strName, TEXT("WAVE") ) ) )
{
if( NULL == ( hResInfo = FindResource( hModule, strName, TEXT("WAV") ) ) )
return E_FAIL;
}
if( NULL == ( hResData = LoadResource( hModule, hResInfo ) ) )
return E_FAIL;
if( NULL == ( pvRes = LockResource( hResData ) ) )
return E_FAIL;
if( FAILED( DSUtil_ParseWaveResource( pvRes, ppWaveHeader, ppbWaveData,
pcbWaveSize ) ) )
return E_FAIL;
return S_OK;
}
//-----------------------------------------------------------------------------
// Name:
// Desc:
//-----------------------------------------------------------------------------
SoundObject* DSUtil_CreateSound( LPCTSTR strName, DWORD dwNumConcurrentBuffers )
{
SoundObject* pSound = NULL;
LPWAVEFORMATEX pWaveHeader;
BYTE* pbData;
DWORD cbData;
if( NULL == g_pDS )
return NULL;
if( dwNumConcurrentBuffers < 1 )
dwNumConcurrentBuffers = 1;
if( SUCCEEDED( DSUtil_GetWaveResource( NULL, strName, &pWaveHeader,
&pbData, &cbData ) ) )
{
pSound = new SoundObject;
pSound->dwNumBuffers = dwNumConcurrentBuffers;
pSound->pbWaveData = pbData;
pSound->cbWaveSize = cbData;
pSound->dwCurrent = 0;
pSound->pdsbBuffers = new LPDIRECTSOUNDBUFFER[dwNumConcurrentBuffers+1];
pSound->pdsbBuffers[0] = DSUtil_LoadSoundBuffer( g_pDS, strName );
for( DWORD i=1; i<pSound->dwNumBuffers; i++ )
{
if( FAILED( g_pDS->DuplicateSoundBuffer( pSound->pdsbBuffers[0],
&pSound->pdsbBuffers[i] ) ) )
{
pSound->pdsbBuffers[i] = DSUtil_LoadSoundBuffer( g_pDS, strName );
if( NULL == pSound->pdsbBuffers[i] )
{
DSUtil_DestroySound( pSound );
pSound = NULL;
break;
}
}
}
}
return pSound;
}
//-----------------------------------------------------------------------------
// Name: DSUtil_DestroySound()
// Desc:
//-----------------------------------------------------------------------------
VOID DSUtil_DestroySound( SoundObject* pSound )
{
if( pSound )
{
for( DWORD i=0; i<pSound->dwNumBuffers; i++ )
{
if( pSound->pdsbBuffers[i] )
pSound->pdsbBuffers[i]->Release();
}
delete pSound->pdsbBuffers;
delete pSound;
}
}
//-----------------------------------------------------------------------------
// Name:
// Desc:
//-----------------------------------------------------------------------------
LPDIRECTSOUNDBUFFER DSUtil_GetFreeSoundBuffer( SoundObject* pSound )
{
HRESULT hr;
DWORD dwStatus;
if( NULL == pSound )
return NULL;
LPDIRECTSOUNDBUFFER pDSB = pSound->pdsbBuffers[pSound->dwCurrent];
if( NULL == pDSB )
return NULL;
hr = pDSB->GetStatus( &dwStatus );
if( FAILED(hr) )
dwStatus = 0;
if( dwStatus & DSBSTATUS_PLAYING )
{
if( pSound->dwNumBuffers <= 1 )
return NULL;
if( ++pSound->dwCurrent >= pSound->dwNumBuffers )
pSound->dwCurrent = 0;
pDSB = pSound->pdsbBuffers[pSound->dwCurrent];
hr = pDSB->GetStatus( &dwStatus);
if( FAILED(hr) )
dwStatus = 0;
if( dwStatus & DSBSTATUS_PLAYING )
{
pDSB->Stop();
pDSB->SetCurrentPosition( 0 );
}
}
if( dwStatus & DSBSTATUS_BUFFERLOST )
{
if( FAILED( pDSB->Restore() ) )
return NULL;
if( FAILED( DSUtil_FillSoundBuffer( pDSB, pSound->pbWaveData,
pSound->cbWaveSize ) ) )
return NULL;
}
return pDSB;
}
//-----------------------------------------------------------------------------
// Name: DSUtil_PlaySound()
// Desc:
//-----------------------------------------------------------------------------
HRESULT DSUtil_PlaySound( SoundObject* pSound, DWORD dwPlayFlags )
{
if( NULL == pSound )
return E_FAIL;
if( !(dwPlayFlags & DSBPLAY_LOOPING) || (pSound->dwNumBuffers == 1) )
{
LPDIRECTSOUNDBUFFER pDSB = DSUtil_GetFreeSoundBuffer( pSound );
if( pDSB )
{
if( SUCCEEDED( pDSB->Play( 0, 0, dwPlayFlags ) ) )
return S_OK;
}
}
return E_FAIL;
}
//-----------------------------------------------------------------------------
// Name: DSUtil_StopSound()
// Desc:
//-----------------------------------------------------------------------------
HRESULT DSUtil_StopSound( SoundObject* pSound )
{
if( NULL == pSound )
return E_FAIL;
for( DWORD i=0; i<pSound->dwNumBuffers; i++ )
{
pSound->pdsbBuffers[i]->Stop();
pSound->pdsbBuffers[i]->SetCurrentPosition( 0 );
}
return S_OK;
}
//-----------------------------------------------------------------------------
// Name:
// Desc:
//-----------------------------------------------------------------------------
HRESULT DSUtil_FillSoundBuffer( LPDIRECTSOUNDBUFFER pDSB, BYTE* pbWaveData,
DWORD dwWaveSize )
{
VOID* pMem1;
VOID* pMem2;
DWORD dwSize1;
DWORD dwSize2;
if( NULL == pDSB || NULL == pbWaveData || 0 == dwWaveSize )
return E_FAIL;
if( FAILED( pDSB->Lock( 0, dwWaveSize, &pMem1, &dwSize1, &pMem2,
&dwSize2, 0 ) ) )
return E_FAIL;
if( 0 != dwSize1 ) CopyMemory( pMem1, pbWaveData, dwSize1 );
if( 0 != dwSize2 ) CopyMemory( pMem2, pbWaveData+dwSize1, dwSize2 );
pDSB->Unlock( pMem1, dwSize1, pMem2, dwSize2);
return S_OK;
}
//-----------------------------------------------------------------------------
// Name:
// Desc:
//-----------------------------------------------------------------------------
HRESULT DSUtil_ParseWaveResource( VOID* pvRes, WAVEFORMATEX** ppWaveHeader,
BYTE** ppbWaveData, DWORD* pcbWaveSize )
{
DWORD* pdw;
DWORD* pdwEnd;
DWORD dwRiff;
DWORD dwType;
DWORD dwLength;
if( ppWaveHeader )
*ppWaveHeader = NULL;
if( ppbWaveData )
*ppbWaveData = NULL;
if( pcbWaveSize )
*pcbWaveSize = 0;
pdw = (DWORD*)pvRes;
dwRiff = *pdw++;
dwLength = *pdw++;
dwType = *pdw++;
if( dwRiff != mmioFOURCC('R', 'I', 'F', 'F') )
return E_FAIL;
if( dwType != mmioFOURCC('W', 'A', 'V', 'E') )
return E_FAIL;
pdwEnd = (DWORD *)((BYTE *)pdw + dwLength-4);
while( pdw < pdwEnd )
{
dwType = *pdw++;
dwLength = *pdw++;
if( dwType == mmioFOURCC('f', 'm', 't', ' ') )
{
if (ppWaveHeader && !*ppWaveHeader)
{
if( dwLength < sizeof(WAVEFORMAT) )
return E_FAIL;
*ppWaveHeader = (WAVEFORMATEX*)pdw;
if( (!ppbWaveData || *ppbWaveData) &&
(!pcbWaveSize || *pcbWaveSize) )
{
return S_OK;
}
}
}
if( dwType == mmioFOURCC('d', 'a', 't', 'a') )
{
if( (ppbWaveData && !*ppbWaveData) ||
(pcbWaveSize && !*pcbWaveSize) )
{
if( ppbWaveData )
*ppbWaveData = (BYTE*)pdw;
if( pcbWaveSize )
*pcbWaveSize = dwLength;
if( !ppWaveHeader || *ppWaveHeader )
return S_OK;
}
}
pdw = (DWORD*)( (BYTE*)pdw + ((dwLength+1)&~1) );
}
return E_FAIL;
}
//-----------------------------------------------------------------------------
// Name: DSUtil_PlayPannedSound()
// Desc: Play a sound, but first set the panning according to where the
// object is on the screen. fScreenXPos is between -1.0f (left) and
// 1.0f (right).
//-----------------------------------------------------------------------------
VOID DSUtil_PlayPannedSound( SoundObject* pSound, FLOAT fScreenXPos )
{
LPDIRECTSOUNDBUFFER pDSB = DSUtil_GetFreeSoundBuffer( pSound );
if( pDSB )
{
pDSB->SetPan( (LONG)( 10000L * fScreenXPos ) );
pDSB->Play( 0, 0, 0 );
}
}
//-----------------------------------------------------------------------------
// Name: DSUtil_InitDirectSound()
// Desc:
//-----------------------------------------------------------------------------
HRESULT DSUtil_InitDirectSound( HWND hWnd )
{
if( FAILED( DirectSoundCreate( NULL, &g_pDS, NULL ) ) )
return E_FAIL;
if( FAILED( g_pDS->SetCooperativeLevel( hWnd, DSSCL_NORMAL ) ) )
{
g_pDS->Release();
g_pDS = NULL;
return E_FAIL;
}
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: DSUtil_FreeDirectSound()
// Desc:
//-----------------------------------------------------------------------------
VOID DSUtil_FreeDirectSound()
{
if( g_pDS )
g_pDS->Release();
g_pDS = NULL;
}

View File

@@ -0,0 +1,152 @@
//-----------------------------------------------------------------------------
// File: dsutil.cpp
//
// Desc: Routines for dealing with sounds from resources
//
// Copyright (C) 1995-2001 Microsoft Corporation. All Rights Reserved.
//-----------------------------------------------------------------------------
#ifndef DSUTIL_H
#define DSUTIL_H
//-----------------------------------------------------------------------------
// Helper routines
//-----------------------------------------------------------------------------
HRESULT DSUtil_FillSoundBuffer( LPDIRECTSOUNDBUFFER pDSB, BYTE* pbWaveData,
DWORD dwWaveSize );
HRESULT DSUtil_ParseWaveResource( VOID* pvRes, WAVEFORMATEX** ppWaveHeader,
BYTE** ppbWaveData, DWORD* pdwWaveSize );
//-----------------------------------------------------------------------------
// Name: DSUtil_LoadSoundBuffer()
// Desc: Loads an IDirectSoundBuffer from a Win32 resource in the current
// application.
//-----------------------------------------------------------------------------
LPDIRECTSOUNDBUFFER DSUtil_LoadSoundBuffer( LPDIRECTSOUND* pDS,
LPCTSTR strName );
//-----------------------------------------------------------------------------
// Name: DSUtil_ReloadSoundBuffer()
// Desc: Reloads an IDirectSoundBuffer from a Win32 resource in the current
// application. normally used to handle a DSERR_BUFFERLOST error.
//-----------------------------------------------------------------------------
HRESULT DSUtil_ReloadSoundBuffer( LPDIRECTSOUNDBUFFER pDSB, LPCTSTR strName );
//-----------------------------------------------------------------------------
// Name: DSUtil_GetWaveResource()
// Desc: Finds a WAV resource in a Win32 module.
//-----------------------------------------------------------------------------
HRESULT DSUtil_GetWaveResource( HMODULE hModule, LPCTSTR strName,
WAVEFORMATEX** ppWaveHeader, BYTE** ppbWaveData,
DWORD* pdwWaveSize );
//-----------------------------------------------------------------------------
// Name: DSUtil_InitDirectSound()
// Desc:
//-----------------------------------------------------------------------------
HRESULT DSUtil_InitDirectSound( HWND hWnd );
//-----------------------------------------------------------------------------
// Name: DSUtil_FreeDirectSound()
// Desc:
//-----------------------------------------------------------------------------
VOID DSUtil_FreeDirectSound();
//-----------------------------------------------------------------------------
// Name: struct SoundObject
// Desc: Used to manage individual sounds which need to be played multiple
// times concurrently. A SoundObject represents a queue of
// IDirectSoundBuffer objects which all refer to the same buffer memory.
//-----------------------------------------------------------------------------
struct SoundObject
{
BYTE* pbWaveData; // Ptr into wave resource (for restore)
DWORD cbWaveSize; // Size of wave data (for restore)
DWORD dwNumBuffers; // Number of sound buffers.
DWORD dwCurrent; // Current sound buffer
LPDIRECTSOUNDBUFFER* pdsbBuffers; // List of sound buffers
};
//-----------------------------------------------------------------------------
// Name: DSUtil_CreateSound()
// Desc: Loads a SoundObject from a Win32 resource in the current application.
//-----------------------------------------------------------------------------
SoundObject* DSUtil_CreateSound( LPCTSTR strName, DWORD dwNumBuffers );
//-----------------------------------------------------------------------------
// Name: DSUtil_DestroySound()
// Desc: Frees a SoundObject and releases all of its buffers.
//-----------------------------------------------------------------------------
VOID DSUtil_DestroySound( SoundObject* pSound );
//-----------------------------------------------------------------------------
// Name: DSUtil_PlayPannedSound()
// Desc: Play a sound, but first set the panning according to where the
// object is on the screen. fScreenXPos is between -1.0f (left) and
// 1.0f (right).
//-----------------------------------------------------------------------------
VOID DSUtil_PlayPannedSound( SoundObject* pSound, FLOAT fScreenXPos );
//-----------------------------------------------------------------------------
// Name: DSUtil_PlaySound()
// Desc: Plays a buffer in a SoundObject.
//-----------------------------------------------------------------------------
HRESULT DSUtil_PlaySound( SoundObject* pSound, DWORD dwPlayFlags );
//-----------------------------------------------------------------------------
// Name: DSUtil_StopSound()
// Desc: Stops one or more buffers in a SoundObject.
//-----------------------------------------------------------------------------
HRESULT DSUtil_StopSound( SoundObject* pSound );
//-----------------------------------------------------------------------------
// Name: DSUtil_GetFreeSoundBuffer()
// Desc: Returns one of the cloned buffers that is not currently playing
//-----------------------------------------------------------------------------
LPDIRECTSOUNDBUFFER DSUtil_GetFreeSoundBuffer( SoundObject* pSound );
#endif // DSUTIL_H

View File

@@ -0,0 +1,690 @@
# Microsoft Developer Studio Generated NMAKE File, Format Version 4.20
# ** DO NOT EDIT **
# TARGTYPE "Win32 (x86) Application" 0x0101
!IF "$(CFG)" == ""
CFG=duel - Win32 Debug
!MESSAGE No configuration specified. Defaulting to duel - Win32 Debug.
!ENDIF
!IF "$(CFG)" != "duel - Win32 Release" && "$(CFG)" != "duel - Win32 Debug"
!MESSAGE Invalid configuration "$(CFG)" specified.
!MESSAGE You can specify a configuration when running NMAKE on this makefile
!MESSAGE by defining the macro CFG on the command line. For example:
!MESSAGE
!MESSAGE NMAKE /f "duel.mak" CFG="duel - Win32 Debug"
!MESSAGE
!MESSAGE Possible choices for configuration are:
!MESSAGE
!MESSAGE "duel - Win32 Release" (based on "Win32 (x86) Application")
!MESSAGE "duel - Win32 Debug" (based on "Win32 (x86) Application")
!MESSAGE
!ERROR An invalid configuration is specified.
!ENDIF
!IF "$(OS)" == "Windows_NT"
NULL=
!ELSE
NULL=nul
!ENDIF
################################################################################
# Begin Project
# PROP Target_Last_Scanned "duel - Win32 Debug"
MTL=mktyplib.exe
CPP=cl.exe
RSC=rc.exe
!IF "$(CFG)" == "duel - Win32 Release"
# PROP BASE Use_MFC 0
# PROP BASE Use_Debug_Libraries 0
# PROP BASE Output_Dir "Release"
# PROP BASE Intermediate_Dir "Release"
# PROP BASE Target_Dir ""
# PROP Use_MFC 0
# PROP Use_Debug_Libraries 0
# PROP Output_Dir "Release"
# PROP Intermediate_Dir "Release"
# PROP Target_Dir ""
OUTDIR=.\Release
INTDIR=.\Release
ALL : "$(OUTDIR)\duel.exe"
CLEAN :
-@erase "$(INTDIR)\ddutil.obj"
-@erase "$(INTDIR)\diutil.obj"
-@erase "$(INTDIR)\dputil.obj"
-@erase "$(INTDIR)\dsutil.obj"
-@erase "$(INTDIR)\duel.obj"
-@erase "$(INTDIR)\duel.res"
-@erase "$(INTDIR)\gameproc.obj"
-@erase "$(INTDIR)\gfx.obj"
-@erase "$(INTDIR)\lobby.obj"
-@erase "$(INTDIR)\util.obj"
-@erase "$(INTDIR)\wizard.obj"
-@erase "$(OUTDIR)\duel.exe"
"$(OUTDIR)" :
if not exist "$(OUTDIR)/$(NULL)" mkdir "$(OUTDIR)"
# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /YX /c
# ADD CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /YX /c
CPP_PROJ=/nologo /ML /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS"\
/Fp"$(INTDIR)/duel.pch" /YX /Fo"$(INTDIR)/" /c
CPP_OBJS=.\Release/
CPP_SBRS=.\.
# ADD BASE MTL /nologo /D "NDEBUG" /win32
# ADD MTL /nologo /D "NDEBUG" /win32
MTL_PROJ=/nologo /D "NDEBUG" /win32
# ADD BASE RSC /l 0x409 /d "NDEBUG"
# ADD RSC /l 0x409 /d "NDEBUG"
RSC_PROJ=/l 0x409 /fo"$(INTDIR)/duel.res" /d "NDEBUG"
BSC32=bscmake.exe
# ADD BASE BSC32 /nologo
# ADD BSC32 /nologo
BSC32_FLAGS=/nologo /o"$(OUTDIR)/duel.bsc"
BSC32_SBRS= \
LINK32=link.exe
# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /subsystem:windows /machine:I386
# ADD LINK32 kernel32.lib user32.lib gdi32.lib ole32.lib comdlg32.lib advapi32.lib shell32.lib uuid.lib comctl32.lib winmm.lib dplayx.lib ddraw.lib dinput.lib dsound.lib /nologo /subsystem:windows /machine:I386
# SUBTRACT LINK32 /nodefaultlib
LINK32_FLAGS=kernel32.lib user32.lib gdi32.lib ole32.lib comdlg32.lib\
advapi32.lib shell32.lib uuid.lib comctl32.lib winmm.lib dplayx.lib ddraw.lib\
dinput.lib dsound.lib /nologo /subsystem:windows /incremental:no\
/pdb:"$(OUTDIR)/duel.pdb" /machine:I386 /out:"$(OUTDIR)/duel.exe"
LINK32_OBJS= \
"$(INTDIR)\ddutil.obj" \
"$(INTDIR)\diutil.obj" \
"$(INTDIR)\dputil.obj" \
"$(INTDIR)\dsutil.obj" \
"$(INTDIR)\duel.obj" \
"$(INTDIR)\duel.res" \
"$(INTDIR)\gameproc.obj" \
"$(INTDIR)\gfx.obj" \
"$(INTDIR)\lobby.obj" \
"$(INTDIR)\util.obj" \
"$(INTDIR)\wizard.obj"
"$(OUTDIR)\duel.exe" : "$(OUTDIR)" $(DEF_FILE) $(LINK32_OBJS)
$(LINK32) @<<
$(LINK32_FLAGS) $(LINK32_OBJS)
<<
!ELSEIF "$(CFG)" == "duel - Win32 Debug"
# PROP BASE Use_MFC 0
# PROP BASE Use_Debug_Libraries 1
# PROP BASE Output_Dir "Debug"
# PROP BASE Intermediate_Dir "Debug"
# PROP BASE Target_Dir ""
# PROP Use_MFC 0
# PROP Use_Debug_Libraries 1
# PROP Output_Dir "Debug"
# PROP Intermediate_Dir "Debug"
# PROP Target_Dir ""
OUTDIR=.\Debug
INTDIR=.\Debug
ALL : "$(OUTDIR)\duel.exe" "$(OUTDIR)\duel.bsc"
CLEAN :
-@erase "$(INTDIR)\ddutil.obj"
-@erase "$(INTDIR)\ddutil.sbr"
-@erase "$(INTDIR)\diutil.obj"
-@erase "$(INTDIR)\diutil.sbr"
-@erase "$(INTDIR)\dputil.obj"
-@erase "$(INTDIR)\dputil.sbr"
-@erase "$(INTDIR)\dsutil.obj"
-@erase "$(INTDIR)\dsutil.sbr"
-@erase "$(INTDIR)\duel.obj"
-@erase "$(INTDIR)\duel.res"
-@erase "$(INTDIR)\duel.sbr"
-@erase "$(INTDIR)\gameproc.obj"
-@erase "$(INTDIR)\gameproc.sbr"
-@erase "$(INTDIR)\gfx.obj"
-@erase "$(INTDIR)\gfx.sbr"
-@erase "$(INTDIR)\lobby.obj"
-@erase "$(INTDIR)\lobby.sbr"
-@erase "$(INTDIR)\util.obj"
-@erase "$(INTDIR)\util.sbr"
-@erase "$(INTDIR)\vc40.idb"
-@erase "$(INTDIR)\vc40.pdb"
-@erase "$(INTDIR)\wizard.obj"
-@erase "$(INTDIR)\wizard.sbr"
-@erase "$(OUTDIR)\duel.bsc"
-@erase "$(OUTDIR)\duel.exe"
-@erase "$(OUTDIR)\duel.ilk"
-@erase "$(OUTDIR)\duel.pdb"
"$(OUTDIR)" :
if not exist "$(OUTDIR)/$(NULL)" mkdir "$(OUTDIR)"
# ADD BASE CPP /nologo /W3 /Gm /GX /Zi /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /YX /c
# ADD CPP /nologo /W3 /Gm /GX /Zi /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /FR /YX /c
CPP_PROJ=/nologo /MLd /W3 /Gm /GX /Zi /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS"\
/FR"$(INTDIR)/" /Fp"$(INTDIR)/duel.pch" /YX /Fo"$(INTDIR)/" /Fd"$(INTDIR)/" /c
CPP_OBJS=.\Debug/
CPP_SBRS=.\Debug/
# ADD BASE MTL /nologo /D "_DEBUG" /win32
# ADD MTL /nologo /D "_DEBUG" /win32
MTL_PROJ=/nologo /D "_DEBUG" /win32
# ADD BASE RSC /l 0x409 /d "_DEBUG"
# ADD RSC /l 0x409 /d "_DEBUG"
RSC_PROJ=/l 0x409 /fo"$(INTDIR)/duel.res" /d "_DEBUG"
BSC32=bscmake.exe
# ADD BASE BSC32 /nologo
# ADD BSC32 /nologo
BSC32_FLAGS=/nologo /o"$(OUTDIR)/duel.bsc"
BSC32_SBRS= \
"$(INTDIR)\ddutil.sbr" \
"$(INTDIR)\diutil.sbr" \
"$(INTDIR)\dputil.sbr" \
"$(INTDIR)\dsutil.sbr" \
"$(INTDIR)\duel.sbr" \
"$(INTDIR)\gameproc.sbr" \
"$(INTDIR)\gfx.sbr" \
"$(INTDIR)\lobby.sbr" \
"$(INTDIR)\util.sbr" \
"$(INTDIR)\wizard.sbr"
"$(OUTDIR)\duel.bsc" : "$(OUTDIR)" $(BSC32_SBRS)
$(BSC32) @<<
$(BSC32_FLAGS) $(BSC32_SBRS)
<<
LINK32=link.exe
# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /subsystem:windows /debug /machine:I386
# ADD LINK32 kernel32.lib user32.lib gdi32.lib ole32.lib comdlg32.lib advapi32.lib shell32.lib uuid.lib comctl32.lib winmm.lib dplayx.lib ddraw.lib dinput.lib dsound.lib /nologo /subsystem:windows /debug /machine:I386
# SUBTRACT LINK32 /nodefaultlib
LINK32_FLAGS=kernel32.lib user32.lib gdi32.lib ole32.lib comdlg32.lib\
advapi32.lib shell32.lib uuid.lib comctl32.lib winmm.lib dplayx.lib ddraw.lib\
dinput.lib dsound.lib /nologo /subsystem:windows /incremental:yes\
/pdb:"$(OUTDIR)/duel.pdb" /debug /machine:I386 /out:"$(OUTDIR)/duel.exe"
LINK32_OBJS= \
"$(INTDIR)\ddutil.obj" \
"$(INTDIR)\diutil.obj" \
"$(INTDIR)\dputil.obj" \
"$(INTDIR)\dsutil.obj" \
"$(INTDIR)\duel.obj" \
"$(INTDIR)\duel.res" \
"$(INTDIR)\gameproc.obj" \
"$(INTDIR)\gfx.obj" \
"$(INTDIR)\lobby.obj" \
"$(INTDIR)\util.obj" \
"$(INTDIR)\wizard.obj"
"$(OUTDIR)\duel.exe" : "$(OUTDIR)" $(DEF_FILE) $(LINK32_OBJS)
$(LINK32) @<<
$(LINK32_FLAGS) $(LINK32_OBJS)
<<
!ENDIF
.c{$(CPP_OBJS)}.obj:
$(CPP) $(CPP_PROJ) $<
.cpp{$(CPP_OBJS)}.obj:
$(CPP) $(CPP_PROJ) $<
.cxx{$(CPP_OBJS)}.obj:
$(CPP) $(CPP_PROJ) $<
.c{$(CPP_SBRS)}.sbr:
$(CPP) $(CPP_PROJ) $<
.cpp{$(CPP_SBRS)}.sbr:
$(CPP) $(CPP_PROJ) $<
.cxx{$(CPP_SBRS)}.sbr:
$(CPP) $(CPP_PROJ) $<
################################################################################
# Begin Target
# Name "duel - Win32 Release"
# Name "duel - Win32 Debug"
!IF "$(CFG)" == "duel - Win32 Release"
!ELSEIF "$(CFG)" == "duel - Win32 Debug"
!ENDIF
################################################################################
# Begin Source File
SOURCE=.\wizard.h
!IF "$(CFG)" == "duel - Win32 Release"
!ELSEIF "$(CFG)" == "duel - Win32 Debug"
!ENDIF
# End Source File
################################################################################
# Begin Source File
SOURCE=.\ddutil.h
!IF "$(CFG)" == "duel - Win32 Release"
!ELSEIF "$(CFG)" == "duel - Win32 Debug"
!ENDIF
# End Source File
################################################################################
# Begin Source File
SOURCE=.\diutil.cpp
DEP_CPP_DIUTI=\
".\diutil.h"\
".\duel.h"\
".\gameproc.h"\
{$(INCLUDE)}"\Dinput.h"\
!IF "$(CFG)" == "duel - Win32 Release"
"$(INTDIR)\diutil.obj" : $(SOURCE) $(DEP_CPP_DIUTI) "$(INTDIR)"
!ELSEIF "$(CFG)" == "duel - Win32 Debug"
"$(INTDIR)\diutil.obj" : $(SOURCE) $(DEP_CPP_DIUTI) "$(INTDIR)"
"$(INTDIR)\diutil.sbr" : $(SOURCE) $(DEP_CPP_DIUTI) "$(INTDIR)"
!ENDIF
# End Source File
################################################################################
# Begin Source File
SOURCE=.\diutil.h
!IF "$(CFG)" == "duel - Win32 Release"
!ELSEIF "$(CFG)" == "duel - Win32 Debug"
!ENDIF
# End Source File
################################################################################
# Begin Source File
SOURCE=.\dputil.cpp
DEP_CPP_DPUTI=\
".\dputil.h"\
".\duel.h"\
".\lobby.h"\
{$(INCLUDE)}"\dplobby.h"\
!IF "$(CFG)" == "duel - Win32 Release"
"$(INTDIR)\dputil.obj" : $(SOURCE) $(DEP_CPP_DPUTI) "$(INTDIR)"
!ELSEIF "$(CFG)" == "duel - Win32 Debug"
"$(INTDIR)\dputil.obj" : $(SOURCE) $(DEP_CPP_DPUTI) "$(INTDIR)"
"$(INTDIR)\dputil.sbr" : $(SOURCE) $(DEP_CPP_DPUTI) "$(INTDIR)"
!ENDIF
# End Source File
################################################################################
# Begin Source File
SOURCE=.\dputil.h
!IF "$(CFG)" == "duel - Win32 Release"
!ELSEIF "$(CFG)" == "duel - Win32 Debug"
!ENDIF
# End Source File
################################################################################
# Begin Source File
SOURCE=.\dsutil.cpp
DEP_CPP_DSUTI=\
".\dsutil.h"\
!IF "$(CFG)" == "duel - Win32 Release"
"$(INTDIR)\dsutil.obj" : $(SOURCE) $(DEP_CPP_DSUTI) "$(INTDIR)"
!ELSEIF "$(CFG)" == "duel - Win32 Debug"
"$(INTDIR)\dsutil.obj" : $(SOURCE) $(DEP_CPP_DSUTI) "$(INTDIR)"
"$(INTDIR)\dsutil.sbr" : $(SOURCE) $(DEP_CPP_DSUTI) "$(INTDIR)"
!ENDIF
# End Source File
################################################################################
# Begin Source File
SOURCE=.\dsutil.h
!IF "$(CFG)" == "duel - Win32 Release"
!ELSEIF "$(CFG)" == "duel - Win32 Debug"
!ENDIF
# End Source File
################################################################################
# Begin Source File
SOURCE=.\duel.cpp
DEP_CPP_DUEL_=\
".\diutil.h"\
".\dputil.h"\
".\dsutil.h"\
".\duel.h"\
".\gameproc.h"\
".\gfx.h"\
".\lobby.h"\
".\wizard.h"\
{$(INCLUDE)}"\Dinput.h"\
{$(INCLUDE)}"\dplobby.h"\
!IF "$(CFG)" == "duel - Win32 Release"
"$(INTDIR)\duel.obj" : $(SOURCE) $(DEP_CPP_DUEL_) "$(INTDIR)"
!ELSEIF "$(CFG)" == "duel - Win32 Debug"
"$(INTDIR)\duel.obj" : $(SOURCE) $(DEP_CPP_DUEL_) "$(INTDIR)"
"$(INTDIR)\duel.sbr" : $(SOURCE) $(DEP_CPP_DUEL_) "$(INTDIR)"
!ENDIF
# End Source File
################################################################################
# Begin Source File
SOURCE=.\duel.h
!IF "$(CFG)" == "duel - Win32 Release"
!ELSEIF "$(CFG)" == "duel - Win32 Debug"
!ENDIF
# End Source File
################################################################################
# Begin Source File
SOURCE=.\duel.rc
DEP_RSC_DUEL_R=\
".\Bfire.wav"\
".\csession.bmp"\
".\DUEL.BMP"\
".\duel.ico"\
".\Lboom.wav"\
".\osession.bmp"\
".\player.bmp"\
".\Sboom.wav"\
".\Sbounce.wav"\
".\Sengine.wav"\
".\SPLASH.BMP"\
".\Sstart.wav"\
".\Sstop.wav"\
".\verinfo.h"\
".\verinfo.ver"\
"$(INTDIR)\duel.res" : $(SOURCE) $(DEP_RSC_DUEL_R) "$(INTDIR)"
$(RSC) $(RSC_PROJ) $(SOURCE)
# End Source File
################################################################################
# Begin Source File
SOURCE=.\gameproc.cpp
DEP_CPP_GAMEP=\
".\diutil.h"\
".\dputil.h"\
".\dsutil.h"\
".\duel.h"\
".\gameproc.h"\
".\gfx.h"\
".\lobby.h"\
".\wizard.h"\
{$(INCLUDE)}"\Dinput.h"\
{$(INCLUDE)}"\dplobby.h"\
!IF "$(CFG)" == "duel - Win32 Release"
"$(INTDIR)\gameproc.obj" : $(SOURCE) $(DEP_CPP_GAMEP) "$(INTDIR)"
!ELSEIF "$(CFG)" == "duel - Win32 Debug"
"$(INTDIR)\gameproc.obj" : $(SOURCE) $(DEP_CPP_GAMEP) "$(INTDIR)"
"$(INTDIR)\gameproc.sbr" : $(SOURCE) $(DEP_CPP_GAMEP) "$(INTDIR)"
!ENDIF
# End Source File
################################################################################
# Begin Source File
SOURCE=.\gameproc.h
!IF "$(CFG)" == "duel - Win32 Release"
!ELSEIF "$(CFG)" == "duel - Win32 Debug"
!ENDIF
# End Source File
################################################################################
# Begin Source File
SOURCE=.\gfx.cpp
DEP_CPP_GFX_C=\
".\ddutil.h"\
".\diutil.h"\
".\duel.h"\
".\gfx.h"\
{$(INCLUDE)}"\Dinput.h"\
!IF "$(CFG)" == "duel - Win32 Release"
"$(INTDIR)\gfx.obj" : $(SOURCE) $(DEP_CPP_GFX_C) "$(INTDIR)"
!ELSEIF "$(CFG)" == "duel - Win32 Debug"
"$(INTDIR)\gfx.obj" : $(SOURCE) $(DEP_CPP_GFX_C) "$(INTDIR)"
"$(INTDIR)\gfx.sbr" : $(SOURCE) $(DEP_CPP_GFX_C) "$(INTDIR)"
!ENDIF
# End Source File
################################################################################
# Begin Source File
SOURCE=.\gfx.h
!IF "$(CFG)" == "duel - Win32 Release"
!ELSEIF "$(CFG)" == "duel - Win32 Debug"
!ENDIF
# End Source File
################################################################################
# Begin Source File
SOURCE=.\lobby.cpp
DEP_CPP_LOBBY=\
".\duel.h"\
".\lobby.h"\
{$(INCLUDE)}"\dplobby.h"\
!IF "$(CFG)" == "duel - Win32 Release"
"$(INTDIR)\lobby.obj" : $(SOURCE) $(DEP_CPP_LOBBY) "$(INTDIR)"
!ELSEIF "$(CFG)" == "duel - Win32 Debug"
"$(INTDIR)\lobby.obj" : $(SOURCE) $(DEP_CPP_LOBBY) "$(INTDIR)"
"$(INTDIR)\lobby.sbr" : $(SOURCE) $(DEP_CPP_LOBBY) "$(INTDIR)"
!ENDIF
# End Source File
################################################################################
# Begin Source File
SOURCE=.\lobby.h
!IF "$(CFG)" == "duel - Win32 Release"
!ELSEIF "$(CFG)" == "duel - Win32 Debug"
!ENDIF
# End Source File
################################################################################
# Begin Source File
SOURCE=.\resource.h
!IF "$(CFG)" == "duel - Win32 Release"
!ELSEIF "$(CFG)" == "duel - Win32 Debug"
!ENDIF
# End Source File
################################################################################
# Begin Source File
SOURCE=.\util.cpp
DEP_CPP_UTIL_=\
".\duel.h"\
!IF "$(CFG)" == "duel - Win32 Release"
"$(INTDIR)\util.obj" : $(SOURCE) $(DEP_CPP_UTIL_) "$(INTDIR)"
!ELSEIF "$(CFG)" == "duel - Win32 Debug"
"$(INTDIR)\util.obj" : $(SOURCE) $(DEP_CPP_UTIL_) "$(INTDIR)"
"$(INTDIR)\util.sbr" : $(SOURCE) $(DEP_CPP_UTIL_) "$(INTDIR)"
!ENDIF
# End Source File
################################################################################
# Begin Source File
SOURCE=.\wizard.cpp
DEP_CPP_WIZAR=\
".\dputil.h"\
".\duel.h"\
".\gameproc.h"\
".\lobby.h"\
".\wizard.h"\
{$(INCLUDE)}"\dplobby.h"\
!IF "$(CFG)" == "duel - Win32 Release"
"$(INTDIR)\wizard.obj" : $(SOURCE) $(DEP_CPP_WIZAR) "$(INTDIR)"
!ELSEIF "$(CFG)" == "duel - Win32 Debug"
"$(INTDIR)\wizard.obj" : $(SOURCE) $(DEP_CPP_WIZAR) "$(INTDIR)"
"$(INTDIR)\wizard.sbr" : $(SOURCE) $(DEP_CPP_WIZAR) "$(INTDIR)"
!ENDIF
# End Source File
################################################################################
# Begin Source File
SOURCE=.\ddutil.cpp
DEP_CPP_DDUTI=\
".\ddutil.h"\
!IF "$(CFG)" == "duel - Win32 Release"
"$(INTDIR)\ddutil.obj" : $(SOURCE) $(DEP_CPP_DDUTI) "$(INTDIR)"
!ELSEIF "$(CFG)" == "duel - Win32 Debug"
"$(INTDIR)\ddutil.obj" : $(SOURCE) $(DEP_CPP_DDUTI) "$(INTDIR)"
"$(INTDIR)\ddutil.sbr" : $(SOURCE) $(DEP_CPP_DDUTI) "$(INTDIR)"
!ENDIF
# End Source File
# End Target
# End Project
################################################################################

Binary file not shown.

After

Width:  |  Height:  |  Size: 166 KiB

View File

@@ -0,0 +1,536 @@
//-----------------------------------------------------------------------------
// File: Duel.cpp
//
// Desc: Multi-player game
//
// Copyright (C) 1995-2001 Microsoft Corporation. All Rights Reserved.
//-----------------------------------------------------------------------------
#include "duel.h"
#include "gameproc.h"
#include "gfx.h"
#include "DPUtil.h"
#include "diutil.h"
#include "dsutil.h"
#include "lobby.h"
//-----------------------------------------------------------------------------
// Globals
//-----------------------------------------------------------------------------
// This GUID allows DirectPlay to find other instances of the same game on
// the network. So it must be unique for every game, and the same for
// every instance of that game. // {33925241-05F8-11d0-8063-00A0C90AE891}
GUID g_AppGUID = { 0x33925241, 0x5f8, 0x11d0, { 0x80, 0x63, 0x0, 0xa0, 0xc9, 0xa, 0xe8, 0x91 } };
extern DWORD g_dwFrameCount;
extern DWORD g_dwFrameTime;
extern int g_nProgramState;
extern SHIP g_OurShip;
extern DPID g_LocalPlayerDPID;
static BOOL g_bReinitialize; // Used for switching display modes
TCHAR g_strAppName[256] = "Duel"; // The name of the sample
HANDLE g_hDPMessageEvent = NULL; // Not used in this sample, needed for DPConnect.cpp
TCHAR g_strLocalPlayerName[MAX_PLAYER_NAME]; // Local player name
TCHAR g_strSessionName[MAX_SESSION_NAME]; // Default session name
TCHAR g_strPreferredProvider[MAX_SESSION_NAME]; // Default preferred provider
LPDPLCONNECTION g_pDPLConnection = NULL;
LPDIRECTPLAYLOBBY3 g_pDPLobby = NULL;
HWND g_hwndMain; // Main application window handle
HKEY g_hDuelKey = NULL; // Duel registry key handle
HINSTANCE g_hInst; // Application instance handle
BOOL g_bShowFrameCount=TRUE; // Show FPS ?
BOOL g_bIsActive; // Is the application active ?
BOOL g_bHostPlayer; // Are we hosting or joining a game
DWORD g_dwKeys; // User keyboard input
DWORD g_dwOldKeys; // Last frame's keyboard input
BOOL g_bFullscreen=FALSE; // Window or FullScreen mode ?
RECT g_rcWindow; // client rectangle of main window
BOOL g_bReliable; // sends are reliable
BOOL g_bAsync; // asynchronous sends
BOOL g_bAsyncSupported; // asynchronous sends supported
BOOL g_bUseProtocol; // DirectPlay Protocol messaging
//-----------------------------------------------------------------------------
// Function prototypes
//-----------------------------------------------------------------------------
extern int DPConnect_StartDirectPlayConnect( HINSTANCE hInst, BOOL bBackTrack = FALSE );
extern HRESULT DPConnect_CheckForLobbyLaunch( BOOL* pbLaunchedByLobby );
LRESULT CALLBACK MainWndproc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam );
HRESULT InitApplication( HINSTANCE hInst );
HRESULT ReadRegKey( HKEY hKey, TCHAR* strName, TCHAR* strValue, DWORD dwLength, TCHAR* strDefault );
HRESULT WriteRegKey( HKEY hKey, TCHAR* strName, TCHAR* strValue );
VOID CleanupApplication();
BOOL WasLaunchedByLobby();
BOOL FinishLobbyLaunch();
VOID DoHelp();
//-----------------------------------------------------------------------------
// Name: WinMain()
// Desc:
//-----------------------------------------------------------------------------
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE, LPSTR, int )
{
MSG msg;
BOOL bLaunchedByLobby;
HRESULT hr;
g_hInst = hInstance;
// Read information from registry
RegCreateKeyEx( HKEY_CURRENT_USER, DUEL_KEY, 0, NULL,
REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL,
&g_hDuelKey, NULL );
ReadRegKey( g_hDuelKey, "Player Name",
g_strLocalPlayerName, MAX_PLAYER_NAME, "" );
ReadRegKey( g_hDuelKey, "Session Name",
g_strSessionName, MAX_SESSION_NAME, "" );
ReadRegKey( g_hDuelKey, "Preferred Provider",
g_strPreferredProvider, MAX_SESSION_NAME, "" );
CoInitialize( NULL );
if( FAILED( InitApplication( hInstance ) ) )
return 0;
// See if we were launched from a lobby server
hr = DPConnect_CheckForLobbyLaunch( &bLaunchedByLobby );
if( FAILED(hr) )
return 1;
if( bLaunchedByLobby )
{
// Start game
PostMessage( g_hwndMain, UM_LAUNCH, 0, 0 );
g_bIsActive = TRUE;
}
g_dwFrameTime = timeGetTime();
while( TRUE )
{
if( g_bIsActive )
{
// Any windows messages ? (returns immediately)
if( PeekMessage( &msg, NULL, 0, 0, PM_NOREMOVE ) )
{
if( !GetMessage( &msg, NULL, 0, 0 ) )
break;
TranslateMessage( &msg );
DispatchMessage( &msg );
}
else
{
// Poll our receive queue. Polling is used in the sample only for simplicity.
// Receiving messages using an event is the recommended way.
if( g_nProgramState != PS_SPLASH )
{
ReceiveMessages();
LobbyMessageReceive(LMR_PROPERTIES);
}
// update screen
if( !UpdateFrame() )
ExitGame(); // posts QUIT msg
}
}
else
{
// Any windows messages ? (blocks until a message arrives)
if( !GetMessage( &msg, NULL, 0, 0 ) )
break;
TranslateMessage( &msg );
DispatchMessage( &msg );
}
}
CoUninitialize();
// Write information to the registry
WriteRegKey( g_hDuelKey, "Player Name", g_strLocalPlayerName );
WriteRegKey( g_hDuelKey, "Session Name", g_strSessionName );
WriteRegKey( g_hDuelKey, "Preferred Provider", g_strPreferredProvider );
return (int)msg.wParam;
}
//-----------------------------------------------------------------------------
// Name: MainWndproc()
// Desc: Callback for all Windows messages
//-----------------------------------------------------------------------------
LRESULT CALLBACK MainWndproc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )
{
PAINTSTRUCT ps;
HDC hdc;
switch( msg )
{
case WM_SIZE:
case WM_MOVE:
// Get the client rectangle
if( g_bFullscreen )
{
SetRect( &g_rcWindow, 0, 0, GetSystemMetrics(SM_CXSCREEN),
GetSystemMetrics(SM_CYSCREEN) );
}
else
{
GetClientRect( hWnd, &g_rcWindow );
ClientToScreen( hWnd, (POINT*)&g_rcWindow );
ClientToScreen( hWnd, (POINT*)&g_rcWindow+1 );
}
break;
case WM_ACTIVATE:
// Ignore this message during reinitializing graphics
if( g_bReinitialize )
return 0;
// When we are deactivated, although we don't update our screen, we
// still need to to empty our receive queue periodically as
// messages will pile up otherwise. Polling the receive queue
// continuously even when we are deactivated causes our app to
// consume all the CPU time. To avoid hogging the CPU, we block on
// GetMessage() WIN API and setup a timer to wake ourselves up at
// regular intervals to process our messages.
if( LOWORD(wParam) == WA_INACTIVE )
{
// Aeactivated
g_bIsActive = FALSE;
if( PS_ACTIVE == g_nProgramState )
SetTimer( hWnd, RECEIVE_TIMER_ID, RECEIVE_TIMEOUT, NULL );
}
else
{
// Activated
g_bIsActive = TRUE;
if( PS_ACTIVE == g_nProgramState )
KillTimer( hWnd, RECEIVE_TIMER_ID );
}
// set game palette, if activated in game mode
if( g_bIsActive && (g_nProgramState != PS_SPLASH) )
SetGamePalette();
DIUtil_ReacquireInputDevices();
return 0;
case WM_CREATE:
break;
case WM_SYSKEYUP:
switch( wParam )
{
// Handle ALT+ENTER (fullscreen/window mode)
case VK_RETURN:
// Mode switch is allowed only during the game
if( g_nProgramState == PS_ACTIVE )
{
g_bReinitialize = TRUE;
ReleaseLocalData(); //only sound buffers have to be rels'd anyway.
CleanupGameSounds();
DIUtil_CleanupInput();
CleanupGraphics();
DestroyWindow( g_hwndMain );
g_bFullscreen = !g_bFullscreen;
InitGraphics();
DIUtil_InitInput( g_hwndMain );
InitializeGameSounds();
InitLocalSoundData();
g_bReinitialize = FALSE;
}
break;
}
break;
case WM_KEYDOWN:
switch( wParam )
{
case 'a':
case 'A':
// Toggle Async sends on/off
if( g_bAsyncSupported )
{
g_bAsync = !g_bAsync;
UpdateTitle(); // caption bar status
}
break;
case 'r':
case 'R':
// Toggle reliable sends
g_bReliable = !g_bReliable;
UpdateTitle();
break;
case VK_F1:
// Display help
DoHelp();
break;
case VK_F5:
// Toggle frame rate display
g_bShowFrameCount = !g_bShowFrameCount;
if( g_bShowFrameCount )
{
g_dwFrameCount = 0;
g_dwFrameTime = timeGetTime();
}
break;
case VK_RETURN:
// Launch game setup wizard
if( (g_nProgramState == PS_SPLASH) && !g_bFullscreen )
{
int nExitCode;
nExitCode = DPConnect_StartDirectPlayConnect( g_hInst, FALSE );
// Figure out what happened, and post a reflecting message
if( nExitCode == EXITCODE_FORWARD )
PostMessage(g_hwndMain, UM_LAUNCH, 0, 0);
if( nExitCode == EXITCODE_QUIT )
PostMessage(g_hwndMain, UM_ABORT, 0, 0);
if( nExitCode == EXITCODE_LOBBYCONNECT )
PostMessage( g_hwndMain, UM_LAUNCH, 0, 0 );
if( nExitCode == EXITCODE_ERROR )
{
MessageBox( g_hwndMain, TEXT("Mutliplayer connect failed. "
"The sample will now quit."),
TEXT("DirectPlay Sample"), MB_OK | MB_ICONERROR );
PostMessage(g_hwndMain, UM_ABORT, 0, 0);
}
}
break;
case VK_ESCAPE:
case VK_F12:
// Exit the game
ExitGame();
return 0;
}
break;
case WM_ERASEBKGND:
return 1;
case WM_PAINT:
hdc = BeginPaint( hWnd, &ps );
if( g_nProgramState == PS_SPLASH )
{
// Display the splash screen
BltSplashScreen( NULL );
}
EndPaint( hWnd, &ps );
return 1;
case UM_LAUNCH:
case UM_ABORT:
// if we were launched by the lobby and not (failed to finish a lobby launch)
// where wParam is bLobbyLaunched
if( msg == UM_LAUNCH )
{
// Init lobby msg support for reporting score
// Note that we don't release the lobby object
LobbyMessageInit();
// Start the game in rest mode
g_nProgramState = PS_REST;
LaunchGame();
return 1;
}
// Else aborting
ExitGame();
return 1;
case WM_TIMER:
ReceiveMessages();
LobbyMessageReceive( LMR_PROPERTIES );
break;
case WM_DESTROY:
// If g_bReinitialize is TRUE don't quit, we are just switching
// display modes
if( !g_bReinitialize )
{
CleanupApplication();
PostQuitMessage( 0 );
}
return 0;
default:
break;
}
return DefWindowProc( hWnd, msg, wParam, lParam );
}
//-----------------------------------------------------------------------------
// Name: InitApplication()
// Desc: Do that initialization stuff...
//-----------------------------------------------------------------------------
HRESULT InitApplication( HINSTANCE hInst )
{
WNDCLASS wndClass = { CS_DBLCLKS, MainWndproc, 0, 0, hInst,
LoadIcon( hInst, MAKEINTRESOURCE(IDI_MAIN)),
LoadCursor(NULL, IDC_ARROW),
(HBRUSH)GetStockObject(BLACK_BRUSH),
NULL, TEXT("DuelClass") };
RegisterClass( &wndClass );
// Initialize all components
if( FAILED( InitGraphics() ) )
return E_FAIL;
if( FAILED( DIUtil_InitInput( g_hwndMain ) ) )
return E_FAIL;
if( FAILED( InitializeGameSounds() ) )
{
// Can play game without sound. Do not exit
}
// Start in splash mode
g_nProgramState = PS_SPLASH;
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: CleanupApplication()
// Desc: Calls clean up on all components
//-----------------------------------------------------------------------------
VOID CleanupApplication()
{
CleanupComm();
CleanupGameSounds();
CleanupGraphics();
DIUtil_CleanupInput();
DPLobbyRelease(); // in case we were doing lobby messages
}
//-----------------------------------------------------------------------------
// Name: ShowError()
// Desc: Displays error to the user
//-----------------------------------------------------------------------------
VOID ShowError( int iStrID )
{
TCHAR strMsg[MAX_ERRORMSG];
LoadString( g_hInst, iStrID, strMsg, MAX_ERRORMSG );
MessageBox( g_hwndMain, strMsg, TEXT("Duel Message"), MB_OK );
}
//-----------------------------------------------------------------------------
// Name: UpdateTitle()
// Desc: Updates the window title based on application status
//-----------------------------------------------------------------------------
VOID UpdateTitle()
{
// Build the window title
TCHAR strTitle[MAX_WINDOWTITLE] = TEXT("Duel");
// State options in window title
if( g_bHostPlayer | g_bUseProtocol | g_bReliable | g_bAsync )
{
strcat( strTitle, " - |" );
if( g_bHostPlayer )
_tcscat( strTitle, TEXT(" Host |") );
if( g_bUseProtocol )
_tcscat( strTitle, TEXT(" Protocol |") );
if( g_bReliable )
_tcscat( strTitle, TEXT(" Reliable |") );
if( g_bAsync )
_tcscat( strTitle, TEXT(" Async |") );
}
// Change window title
SetWindowText( g_hwndMain, strTitle );
}
//-----------------------------------------------------------------------------
// Name: DoHelp()
// Desc: Display a Help summary in a message box.
//-----------------------------------------------------------------------------
VOID DoHelp()
{
TCHAR strHelpMsg[MAX_HELPMSG];
LoadString( g_hInst, IDS_DUEL_HELP, strHelpMsg, MAX_HELPMSG );
MessageBox( g_hwndMain, strHelpMsg, TEXT("DUEL"), MB_OK );
}
//-----------------------------------------------------------------------------
// Name: ReadRegKey()
// Desc: Read a registry key
//-----------------------------------------------------------------------------
HRESULT ReadRegKey( HKEY hKey, TCHAR* strName, TCHAR* strValue,
DWORD dwLength, TCHAR* strDefault )
{
DWORD dwType;
LONG bResult;
bResult = RegQueryValueEx( hKey, strName, 0, &dwType,
(LPBYTE) strValue, &dwLength );
if ( bResult != ERROR_SUCCESS )
strcpy( strValue, strDefault );
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: WriteRegKey()
// Desc: Writes a registry key
//-----------------------------------------------------------------------------
HRESULT WriteRegKey( HKEY hKey, TCHAR* strName, TCHAR* strValue )
{
LONG bResult;
bResult = RegSetValueEx( hKey, strName, 0, REG_SZ,
(LPBYTE) strValue, strlen(strValue) + 1 );
if ( bResult != ERROR_SUCCESS )
return E_FAIL;
return S_OK;
}

View File

@@ -0,0 +1,237 @@
# Microsoft Developer Studio Project File - Name="duel" - Package Owner=<4>
# Microsoft Developer Studio Generated Build File, Format Version 6.00
# ** DO NOT EDIT **
# TARGTYPE "Win32 (x86) Application" 0x0101
CFG=duel - Win32 Release
!MESSAGE This is not a valid makefile. To build this project using NMAKE,
!MESSAGE use the Export Makefile command and run
!MESSAGE
!MESSAGE NMAKE /f "duel.mak".
!MESSAGE
!MESSAGE You can specify a configuration when running NMAKE
!MESSAGE by defining the macro CFG on the command line. For example:
!MESSAGE
!MESSAGE NMAKE /f "duel.mak" CFG="duel - Win32 Release"
!MESSAGE
!MESSAGE Possible choices for configuration are:
!MESSAGE
!MESSAGE "duel - Win32 Release" (based on "Win32 (x86) Application")
!MESSAGE "duel - Win32 Debug" (based on "Win32 (x86) Application")
!MESSAGE
# Begin Project
# PROP AllowPerConfigDependencies 0
# PROP Scc_ProjName ""
# PROP Scc_LocalPath ""
CPP=cl.exe
MTL=midl.exe
RSC=rc.exe
!IF "$(CFG)" == "duel - Win32 Release"
# PROP BASE Use_MFC 0
# PROP BASE Use_Debug_Libraries 0
# PROP BASE Output_Dir ".\Release"
# PROP BASE Intermediate_Dir ".\Release"
# PROP BASE Target_Dir ""
# PROP Use_MFC 0
# PROP Use_Debug_Libraries 0
# PROP Output_Dir ".\Release"
# PROP Intermediate_Dir ".\Release"
# PROP Ignore_Export_Lib 0
# PROP Target_Dir ""
# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /YX /c
# ADD CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /YX /FD /c
# ADD BASE MTL /nologo /D "NDEBUG" /win32
# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32
# ADD BASE RSC /l 0x409 /d "NDEBUG"
# ADD RSC /l 0x409 /d "NDEBUG"
BSC32=bscmake.exe
# ADD BASE BSC32 /nologo
# ADD BSC32 /nologo
LINK32=link.exe
# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /subsystem:windows /machine:I386
# ADD LINK32 uuid.lib comctl32.lib dplayx.lib ddraw.lib dinput.lib dsound.lib dxguid.lib dxerr8.lib ole32.lib winmm.lib kernel32.lib user32.lib gdi32.lib comdlg32.lib advapi32.lib shell32.lib /nologo /subsystem:windows /machine:I386 /stack:0x1f4000,0x1f4000
# SUBTRACT LINK32 /nodefaultlib
!ELSEIF "$(CFG)" == "duel - Win32 Debug"
# PROP BASE Use_MFC 0
# PROP BASE Use_Debug_Libraries 1
# PROP BASE Output_Dir ".\Debug"
# PROP BASE Intermediate_Dir ".\Debug"
# PROP BASE Target_Dir ""
# PROP Use_MFC 0
# PROP Use_Debug_Libraries 1
# PROP Output_Dir ".\Debug"
# PROP Intermediate_Dir ".\Debug"
# PROP Ignore_Export_Lib 0
# PROP Target_Dir ""
# ADD BASE CPP /nologo /W3 /Gm /GX /Zi /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /YX /c
# ADD CPP /nologo /W3 /Gm /GX /Zi /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /FR /YX /FD /c
# ADD BASE MTL /nologo /D "_DEBUG" /win32
# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32
# ADD BASE RSC /l 0x409 /d "_DEBUG"
# ADD RSC /l 0x409 /d "_DEBUG"
BSC32=bscmake.exe
# ADD BASE BSC32 /nologo
# ADD BSC32 /nologo
LINK32=link.exe
# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /subsystem:windows /debug /machine:I386
# ADD LINK32 uuid.lib comctl32.lib dplayx.lib ddraw.lib dinput.lib dsound.lib dxguid.lib dxerr8.lib ole32.lib winmm.lib kernel32.lib user32.lib gdi32.lib comdlg32.lib advapi32.lib shell32.lib /nologo /subsystem:windows /debug /machine:I386 /stack:0x1f4000,0x1f4000
# SUBTRACT LINK32 /nodefaultlib
!ENDIF
# Begin Target
# Name "duel - Win32 Release"
# Name "duel - Win32 Debug"
# Begin Group "Source Files"
# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat;for;f90"
# Begin Source File
SOURCE=.\ddutil.cpp
# End Source File
# Begin Source File
SOURCE=.\ddutil.h
# End Source File
# Begin Source File
SOURCE=.\diutil.cpp
# End Source File
# Begin Source File
SOURCE=.\diutil.h
# End Source File
# Begin Source File
SOURCE=.\dpconnect.cpp
# End Source File
# Begin Source File
SOURCE=.\dputil.cpp
# End Source File
# Begin Source File
SOURCE=.\dputil.h
# End Source File
# Begin Source File
SOURCE=.\dsutil.cpp
# End Source File
# Begin Source File
SOURCE=.\dsutil.h
# End Source File
# Begin Source File
SOURCE=.\duel.cpp
# End Source File
# Begin Source File
SOURCE=.\duel.h
# End Source File
# Begin Source File
SOURCE=.\duel.rc
# End Source File
# Begin Source File
SOURCE=.\gameproc.cpp
# End Source File
# Begin Source File
SOURCE=.\gameproc.h
# End Source File
# Begin Source File
SOURCE=.\gfx.cpp
# End Source File
# Begin Source File
SOURCE=.\gfx.h
# End Source File
# Begin Source File
SOURCE=.\lobby.cpp
# End Source File
# Begin Source File
SOURCE=.\lobby.h
# End Source File
# Begin Source File
SOURCE=.\resource.h
# End Source File
# Begin Source File
SOURCE=.\util.cpp
# End Source File
# End Group
# Begin Group "Header Files"
# PROP Default_Filter "h;hpp;hxx;hm;inl;fi;fd"
# End Group
# Begin Group "Resource Files"
# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;cnt;rtf;gif;jpg;jpeg;jpe"
# Begin Source File
SOURCE=.\csession.bmp
# End Source File
# Begin Source File
SOURCE=.\DUEL.BMP
# End Source File
# Begin Source File
SOURCE=.\duel.ico
# End Source File
# Begin Source File
SOURCE=.\osession.bmp
# End Source File
# Begin Source File
SOURCE=.\player.bmp
# End Source File
# Begin Source File
SOURCE=.\SPLASH.BMP
# End Source File
# End Group
# Begin Source File
SOURCE=.\Bfire.wav
# End Source File
# Begin Source File
SOURCE=.\Lboom.wav
# End Source File
# Begin Source File
SOURCE=.\Sboom.wav
# End Source File
# Begin Source File
SOURCE=.\Sbounce.wav
# End Source File
# Begin Source File
SOURCE=.\Sengine.wav
# End Source File
# Begin Source File
SOURCE=.\Sstart.wav
# End Source File
# Begin Source File
SOURCE=.\Sstop.wav
# End Source File
# End Target
# End Project

View File

@@ -0,0 +1,29 @@
Microsoft Developer Studio Workspace File, Format Version 6.00
# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE!
###############################################################################
Project: "duel"=.\duel.dsp - Package Owner=<4>
Package=<5>
{{{
}}}
Package=<4>
{{{
}}}
###############################################################################
Global:
Package=<5>
{{{
}}}
Package=<3>
{{{
}}}
###############################################################################

View File

@@ -0,0 +1,97 @@
//-----------------------------------------------------------------------------
// File: Duel.h
//
// Desc: Duel include file
//
// Copyright (C) 1995-2001 Microsoft Corporation. All Rights Reserved.
//-----------------------------------------------------------------------------
#ifndef DUEL_INCLUDED
#define DUEL_INCLUDED
// bcc32 does not support nameless unions in C mode
#if defined(__BORLANDC__) && !defined(__cplusplus)
#define NONAMELESSUNION
#endif
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#include <windowsx.h>
#include <mmsystem.h>
#include "resource.h"
#include <wtypes.h>
#include <tchar.h>
//-----------------------------------------------------------------------------
// Application constants
//-----------------------------------------------------------------------------
// Dialog exit codes
#define EXITCODE_FORWARD 1 // Dialog success, so go forward
#define EXITCODE_BACKUP 2 // Dialog canceled, show previous dialog
#define EXITCODE_QUIT 3 // Dialog quit, close app
#define EXITCODE_ERROR 4 // Dialog error, terminate app
#define EXITCODE_LOBBYCONNECT 5 // Dialog connected from lobby, connect success
// User messages
#define UM_LAUNCH WM_USER
#define UM_ABORT WM_USER+1
#define UM_RESTARTTIMER WM_USER+2
// program states
enum{ PS_SPLASH, PS_ACTIVE, PS_REST };
#define MAX_SCREEN_X 639
#define MAX_SCREEN_Y 479
#define MAX_PLAYER_NAME 14
#define MAX_SESSION_NAME 256
#define MAX_SPNAME 50
#define MAX_CLASSNAME 50
#define MAX_WINDOWTITLE 50
#define MAX_ERRORMSG 256
#define MAX_FONTNAME 50
#define MAX_HELPMSG 512
#define RECEIVE_TIMER_ID 1
#define RECEIVE_TIMEOUT 1000 // in milliseconds
#define ENUM_TIMER_ID 2
#define ENUM_TIMEOUT 2000 // in milliseconds
// Default window size
#define MAX_DEFWIN_X 640
#define MAX_DEFWIN_Y 480
// Tree view image info
#define CX_BITMAP 25
#define CY_BITMAP 25
#define NUM_BITMAPS 2
// registry info
#define DUEL_KEY (TEXT("Software\\Microsoft\\Duel"))
//-----------------------------------------------------------------------------
// Prototypes
//-----------------------------------------------------------------------------
VOID ShowError( int err );
VOID UpdateTitle();
// Functions defined in util.c
int randInt( int low, int high );
double randDouble( double low, double high );
#define TRACE dtrace
void dtrace( TCHAR* strFormat, ...);
#endif

Binary file not shown.

After

Width:  |  Height:  |  Size: 766 B

View File

@@ -0,0 +1,690 @@
# Microsoft Developer Studio Generated NMAKE File, Format Version 4.20
# ** DO NOT EDIT **
# TARGTYPE "Win32 (x86) Application" 0x0101
!IF "$(CFG)" == ""
CFG=duel - Win32 Debug
!MESSAGE No configuration specified. Defaulting to duel - Win32 Debug.
!ENDIF
!IF "$(CFG)" != "duel - Win32 Release" && "$(CFG)" != "duel - Win32 Debug"
!MESSAGE Invalid configuration "$(CFG)" specified.
!MESSAGE You can specify a configuration when running NMAKE on this makefile
!MESSAGE by defining the macro CFG on the command line. For example:
!MESSAGE
!MESSAGE NMAKE /f "duel.mak" CFG="duel - Win32 Debug"
!MESSAGE
!MESSAGE Possible choices for configuration are:
!MESSAGE
!MESSAGE "duel - Win32 Release" (based on "Win32 (x86) Application")
!MESSAGE "duel - Win32 Debug" (based on "Win32 (x86) Application")
!MESSAGE
!ERROR An invalid configuration is specified.
!ENDIF
!IF "$(OS)" == "Windows_NT"
NULL=
!ELSE
NULL=nul
!ENDIF
################################################################################
# Begin Project
# PROP Target_Last_Scanned "duel - Win32 Debug"
MTL=mktyplib.exe
CPP=cl.exe
RSC=rc.exe
!IF "$(CFG)" == "duel - Win32 Release"
# PROP BASE Use_MFC 0
# PROP BASE Use_Debug_Libraries 0
# PROP BASE Output_Dir "Release"
# PROP BASE Intermediate_Dir "Release"
# PROP BASE Target_Dir ""
# PROP Use_MFC 0
# PROP Use_Debug_Libraries 0
# PROP Output_Dir "Release"
# PROP Intermediate_Dir "Release"
# PROP Target_Dir ""
OUTDIR=.\Release
INTDIR=.\Release
ALL : "$(OUTDIR)\duel.exe"
CLEAN :
-@erase "$(INTDIR)\ddutil.obj"
-@erase "$(INTDIR)\diutil.obj"
-@erase "$(INTDIR)\dputil.obj"
-@erase "$(INTDIR)\dsutil.obj"
-@erase "$(INTDIR)\duel.obj"
-@erase "$(INTDIR)\duel.res"
-@erase "$(INTDIR)\gameproc.obj"
-@erase "$(INTDIR)\gfx.obj"
-@erase "$(INTDIR)\lobby.obj"
-@erase "$(INTDIR)\util.obj"
-@erase "$(INTDIR)\wizard.obj"
-@erase "$(OUTDIR)\duel.exe"
"$(OUTDIR)" :
if not exist "$(OUTDIR)/$(NULL)" mkdir "$(OUTDIR)"
# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /YX /c
# ADD CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /YX /c
CPP_PROJ=/nologo /ML /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS"\
/Fp"$(INTDIR)/duel.pch" /YX /Fo"$(INTDIR)/" /c
CPP_OBJS=.\Release/
CPP_SBRS=.\.
# ADD BASE MTL /nologo /D "NDEBUG" /win32
# ADD MTL /nologo /D "NDEBUG" /win32
MTL_PROJ=/nologo /D "NDEBUG" /win32
# ADD BASE RSC /l 0x409 /d "NDEBUG"
# ADD RSC /l 0x409 /d "NDEBUG"
RSC_PROJ=/l 0x409 /fo"$(INTDIR)/duel.res" /d "NDEBUG"
BSC32=bscmake.exe
# ADD BASE BSC32 /nologo
# ADD BSC32 /nologo
BSC32_FLAGS=/nologo /o"$(OUTDIR)/duel.bsc"
BSC32_SBRS= \
LINK32=link.exe
# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /subsystem:windows /machine:I386
# ADD LINK32 kernel32.lib user32.lib gdi32.lib ole32.lib comdlg32.lib advapi32.lib shell32.lib uuid.lib comctl32.lib winmm.lib dplayx.lib ddraw.lib dinput.lib dsound.lib /nologo /subsystem:windows /machine:I386
# SUBTRACT LINK32 /nodefaultlib
LINK32_FLAGS=kernel32.lib user32.lib gdi32.lib ole32.lib comdlg32.lib\
advapi32.lib shell32.lib uuid.lib comctl32.lib winmm.lib dplayx.lib ddraw.lib\
dinput.lib dsound.lib /nologo /subsystem:windows /incremental:no\
/pdb:"$(OUTDIR)/duel.pdb" /machine:I386 /out:"$(OUTDIR)/duel.exe"
LINK32_OBJS= \
"$(INTDIR)\ddutil.obj" \
"$(INTDIR)\diutil.obj" \
"$(INTDIR)\dputil.obj" \
"$(INTDIR)\dsutil.obj" \
"$(INTDIR)\duel.obj" \
"$(INTDIR)\duel.res" \
"$(INTDIR)\gameproc.obj" \
"$(INTDIR)\gfx.obj" \
"$(INTDIR)\lobby.obj" \
"$(INTDIR)\util.obj" \
"$(INTDIR)\wizard.obj"
"$(OUTDIR)\duel.exe" : "$(OUTDIR)" $(DEF_FILE) $(LINK32_OBJS)
$(LINK32) @<<
$(LINK32_FLAGS) $(LINK32_OBJS)
<<
!ELSEIF "$(CFG)" == "duel - Win32 Debug"
# PROP BASE Use_MFC 0
# PROP BASE Use_Debug_Libraries 1
# PROP BASE Output_Dir "Debug"
# PROP BASE Intermediate_Dir "Debug"
# PROP BASE Target_Dir ""
# PROP Use_MFC 0
# PROP Use_Debug_Libraries 1
# PROP Output_Dir "Debug"
# PROP Intermediate_Dir "Debug"
# PROP Target_Dir ""
OUTDIR=.\Debug
INTDIR=.\Debug
ALL : "$(OUTDIR)\duel.exe" "$(OUTDIR)\duel.bsc"
CLEAN :
-@erase "$(INTDIR)\ddutil.obj"
-@erase "$(INTDIR)\ddutil.sbr"
-@erase "$(INTDIR)\diutil.obj"
-@erase "$(INTDIR)\diutil.sbr"
-@erase "$(INTDIR)\dputil.obj"
-@erase "$(INTDIR)\dputil.sbr"
-@erase "$(INTDIR)\dsutil.obj"
-@erase "$(INTDIR)\dsutil.sbr"
-@erase "$(INTDIR)\duel.obj"
-@erase "$(INTDIR)\duel.res"
-@erase "$(INTDIR)\duel.sbr"
-@erase "$(INTDIR)\gameproc.obj"
-@erase "$(INTDIR)\gameproc.sbr"
-@erase "$(INTDIR)\gfx.obj"
-@erase "$(INTDIR)\gfx.sbr"
-@erase "$(INTDIR)\lobby.obj"
-@erase "$(INTDIR)\lobby.sbr"
-@erase "$(INTDIR)\util.obj"
-@erase "$(INTDIR)\util.sbr"
-@erase "$(INTDIR)\vc40.idb"
-@erase "$(INTDIR)\vc40.pdb"
-@erase "$(INTDIR)\wizard.obj"
-@erase "$(INTDIR)\wizard.sbr"
-@erase "$(OUTDIR)\duel.bsc"
-@erase "$(OUTDIR)\duel.exe"
-@erase "$(OUTDIR)\duel.ilk"
-@erase "$(OUTDIR)\duel.pdb"
"$(OUTDIR)" :
if not exist "$(OUTDIR)/$(NULL)" mkdir "$(OUTDIR)"
# ADD BASE CPP /nologo /W3 /Gm /GX /Zi /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /YX /c
# ADD CPP /nologo /W3 /Gm /GX /Zi /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /FR /YX /c
CPP_PROJ=/nologo /MLd /W3 /Gm /GX /Zi /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS"\
/FR"$(INTDIR)/" /Fp"$(INTDIR)/duel.pch" /YX /Fo"$(INTDIR)/" /Fd"$(INTDIR)/" /c
CPP_OBJS=.\Debug/
CPP_SBRS=.\Debug/
# ADD BASE MTL /nologo /D "_DEBUG" /win32
# ADD MTL /nologo /D "_DEBUG" /win32
MTL_PROJ=/nologo /D "_DEBUG" /win32
# ADD BASE RSC /l 0x409 /d "_DEBUG"
# ADD RSC /l 0x409 /d "_DEBUG"
RSC_PROJ=/l 0x409 /fo"$(INTDIR)/duel.res" /d "_DEBUG"
BSC32=bscmake.exe
# ADD BASE BSC32 /nologo
# ADD BSC32 /nologo
BSC32_FLAGS=/nologo /o"$(OUTDIR)/duel.bsc"
BSC32_SBRS= \
"$(INTDIR)\ddutil.sbr" \
"$(INTDIR)\diutil.sbr" \
"$(INTDIR)\dputil.sbr" \
"$(INTDIR)\dsutil.sbr" \
"$(INTDIR)\duel.sbr" \
"$(INTDIR)\gameproc.sbr" \
"$(INTDIR)\gfx.sbr" \
"$(INTDIR)\lobby.sbr" \
"$(INTDIR)\util.sbr" \
"$(INTDIR)\wizard.sbr"
"$(OUTDIR)\duel.bsc" : "$(OUTDIR)" $(BSC32_SBRS)
$(BSC32) @<<
$(BSC32_FLAGS) $(BSC32_SBRS)
<<
LINK32=link.exe
# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /subsystem:windows /debug /machine:I386
# ADD LINK32 kernel32.lib user32.lib gdi32.lib ole32.lib comdlg32.lib advapi32.lib shell32.lib uuid.lib comctl32.lib winmm.lib dplayx.lib ddraw.lib dinput.lib dsound.lib /nologo /subsystem:windows /debug /machine:I386
# SUBTRACT LINK32 /nodefaultlib
LINK32_FLAGS=kernel32.lib user32.lib gdi32.lib ole32.lib comdlg32.lib\
advapi32.lib shell32.lib uuid.lib comctl32.lib winmm.lib dplayx.lib ddraw.lib\
dinput.lib dsound.lib /nologo /subsystem:windows /incremental:yes\
/pdb:"$(OUTDIR)/duel.pdb" /debug /machine:I386 /out:"$(OUTDIR)/duel.exe"
LINK32_OBJS= \
"$(INTDIR)\ddutil.obj" \
"$(INTDIR)\diutil.obj" \
"$(INTDIR)\dputil.obj" \
"$(INTDIR)\dsutil.obj" \
"$(INTDIR)\duel.obj" \
"$(INTDIR)\duel.res" \
"$(INTDIR)\gameproc.obj" \
"$(INTDIR)\gfx.obj" \
"$(INTDIR)\lobby.obj" \
"$(INTDIR)\util.obj" \
"$(INTDIR)\wizard.obj"
"$(OUTDIR)\duel.exe" : "$(OUTDIR)" $(DEF_FILE) $(LINK32_OBJS)
$(LINK32) @<<
$(LINK32_FLAGS) $(LINK32_OBJS)
<<
!ENDIF
.c{$(CPP_OBJS)}.obj:
$(CPP) $(CPP_PROJ) $<
.cpp{$(CPP_OBJS)}.obj:
$(CPP) $(CPP_PROJ) $<
.cxx{$(CPP_OBJS)}.obj:
$(CPP) $(CPP_PROJ) $<
.c{$(CPP_SBRS)}.sbr:
$(CPP) $(CPP_PROJ) $<
.cpp{$(CPP_SBRS)}.sbr:
$(CPP) $(CPP_PROJ) $<
.cxx{$(CPP_SBRS)}.sbr:
$(CPP) $(CPP_PROJ) $<
################################################################################
# Begin Target
# Name "duel - Win32 Release"
# Name "duel - Win32 Debug"
!IF "$(CFG)" == "duel - Win32 Release"
!ELSEIF "$(CFG)" == "duel - Win32 Debug"
!ENDIF
################################################################################
# Begin Source File
SOURCE=.\wizard.h
!IF "$(CFG)" == "duel - Win32 Release"
!ELSEIF "$(CFG)" == "duel - Win32 Debug"
!ENDIF
# End Source File
################################################################################
# Begin Source File
SOURCE=.\ddutil.h
!IF "$(CFG)" == "duel - Win32 Release"
!ELSEIF "$(CFG)" == "duel - Win32 Debug"
!ENDIF
# End Source File
################################################################################
# Begin Source File
SOURCE=.\diutil.cpp
DEP_CPP_DIUTI=\
".\diutil.h"\
".\duel.h"\
".\gameproc.h"\
{$(INCLUDE)}"\Dinput.h"\
!IF "$(CFG)" == "duel - Win32 Release"
"$(INTDIR)\diutil.obj" : $(SOURCE) $(DEP_CPP_DIUTI) "$(INTDIR)"
!ELSEIF "$(CFG)" == "duel - Win32 Debug"
"$(INTDIR)\diutil.obj" : $(SOURCE) $(DEP_CPP_DIUTI) "$(INTDIR)"
"$(INTDIR)\diutil.sbr" : $(SOURCE) $(DEP_CPP_DIUTI) "$(INTDIR)"
!ENDIF
# End Source File
################################################################################
# Begin Source File
SOURCE=.\diutil.h
!IF "$(CFG)" == "duel - Win32 Release"
!ELSEIF "$(CFG)" == "duel - Win32 Debug"
!ENDIF
# End Source File
################################################################################
# Begin Source File
SOURCE=.\dputil.cpp
DEP_CPP_DPUTI=\
".\dputil.h"\
".\duel.h"\
".\lobby.h"\
{$(INCLUDE)}"\dplobby.h"\
!IF "$(CFG)" == "duel - Win32 Release"
"$(INTDIR)\dputil.obj" : $(SOURCE) $(DEP_CPP_DPUTI) "$(INTDIR)"
!ELSEIF "$(CFG)" == "duel - Win32 Debug"
"$(INTDIR)\dputil.obj" : $(SOURCE) $(DEP_CPP_DPUTI) "$(INTDIR)"
"$(INTDIR)\dputil.sbr" : $(SOURCE) $(DEP_CPP_DPUTI) "$(INTDIR)"
!ENDIF
# End Source File
################################################################################
# Begin Source File
SOURCE=.\dputil.h
!IF "$(CFG)" == "duel - Win32 Release"
!ELSEIF "$(CFG)" == "duel - Win32 Debug"
!ENDIF
# End Source File
################################################################################
# Begin Source File
SOURCE=.\dsutil.cpp
DEP_CPP_DSUTI=\
".\dsutil.h"\
!IF "$(CFG)" == "duel - Win32 Release"
"$(INTDIR)\dsutil.obj" : $(SOURCE) $(DEP_CPP_DSUTI) "$(INTDIR)"
!ELSEIF "$(CFG)" == "duel - Win32 Debug"
"$(INTDIR)\dsutil.obj" : $(SOURCE) $(DEP_CPP_DSUTI) "$(INTDIR)"
"$(INTDIR)\dsutil.sbr" : $(SOURCE) $(DEP_CPP_DSUTI) "$(INTDIR)"
!ENDIF
# End Source File
################################################################################
# Begin Source File
SOURCE=.\dsutil.h
!IF "$(CFG)" == "duel - Win32 Release"
!ELSEIF "$(CFG)" == "duel - Win32 Debug"
!ENDIF
# End Source File
################################################################################
# Begin Source File
SOURCE=.\duel.cpp
DEP_CPP_DUEL_=\
".\diutil.h"\
".\dputil.h"\
".\dsutil.h"\
".\duel.h"\
".\gameproc.h"\
".\gfx.h"\
".\lobby.h"\
".\wizard.h"\
{$(INCLUDE)}"\Dinput.h"\
{$(INCLUDE)}"\dplobby.h"\
!IF "$(CFG)" == "duel - Win32 Release"
"$(INTDIR)\duel.obj" : $(SOURCE) $(DEP_CPP_DUEL_) "$(INTDIR)"
!ELSEIF "$(CFG)" == "duel - Win32 Debug"
"$(INTDIR)\duel.obj" : $(SOURCE) $(DEP_CPP_DUEL_) "$(INTDIR)"
"$(INTDIR)\duel.sbr" : $(SOURCE) $(DEP_CPP_DUEL_) "$(INTDIR)"
!ENDIF
# End Source File
################################################################################
# Begin Source File
SOURCE=.\duel.h
!IF "$(CFG)" == "duel - Win32 Release"
!ELSEIF "$(CFG)" == "duel - Win32 Debug"
!ENDIF
# End Source File
################################################################################
# Begin Source File
SOURCE=.\duel.rc
DEP_RSC_DUEL_R=\
".\Bfire.wav"\
".\csession.bmp"\
".\DUEL.BMP"\
".\duel.ico"\
".\Lboom.wav"\
".\osession.bmp"\
".\player.bmp"\
".\Sboom.wav"\
".\Sbounce.wav"\
".\Sengine.wav"\
".\SPLASH.BMP"\
".\Sstart.wav"\
".\Sstop.wav"\
".\verinfo.h"\
".\verinfo.ver"\
"$(INTDIR)\duel.res" : $(SOURCE) $(DEP_RSC_DUEL_R) "$(INTDIR)"
$(RSC) $(RSC_PROJ) $(SOURCE)
# End Source File
################################################################################
# Begin Source File
SOURCE=.\gameproc.cpp
DEP_CPP_GAMEP=\
".\diutil.h"\
".\dputil.h"\
".\dsutil.h"\
".\duel.h"\
".\gameproc.h"\
".\gfx.h"\
".\lobby.h"\
".\wizard.h"\
{$(INCLUDE)}"\Dinput.h"\
{$(INCLUDE)}"\dplobby.h"\
!IF "$(CFG)" == "duel - Win32 Release"
"$(INTDIR)\gameproc.obj" : $(SOURCE) $(DEP_CPP_GAMEP) "$(INTDIR)"
!ELSEIF "$(CFG)" == "duel - Win32 Debug"
"$(INTDIR)\gameproc.obj" : $(SOURCE) $(DEP_CPP_GAMEP) "$(INTDIR)"
"$(INTDIR)\gameproc.sbr" : $(SOURCE) $(DEP_CPP_GAMEP) "$(INTDIR)"
!ENDIF
# End Source File
################################################################################
# Begin Source File
SOURCE=.\gameproc.h
!IF "$(CFG)" == "duel - Win32 Release"
!ELSEIF "$(CFG)" == "duel - Win32 Debug"
!ENDIF
# End Source File
################################################################################
# Begin Source File
SOURCE=.\gfx.cpp
DEP_CPP_GFX_C=\
".\ddutil.h"\
".\diutil.h"\
".\duel.h"\
".\gfx.h"\
{$(INCLUDE)}"\Dinput.h"\
!IF "$(CFG)" == "duel - Win32 Release"
"$(INTDIR)\gfx.obj" : $(SOURCE) $(DEP_CPP_GFX_C) "$(INTDIR)"
!ELSEIF "$(CFG)" == "duel - Win32 Debug"
"$(INTDIR)\gfx.obj" : $(SOURCE) $(DEP_CPP_GFX_C) "$(INTDIR)"
"$(INTDIR)\gfx.sbr" : $(SOURCE) $(DEP_CPP_GFX_C) "$(INTDIR)"
!ENDIF
# End Source File
################################################################################
# Begin Source File
SOURCE=.\gfx.h
!IF "$(CFG)" == "duel - Win32 Release"
!ELSEIF "$(CFG)" == "duel - Win32 Debug"
!ENDIF
# End Source File
################################################################################
# Begin Source File
SOURCE=.\lobby.cpp
DEP_CPP_LOBBY=\
".\duel.h"\
".\lobby.h"\
{$(INCLUDE)}"\dplobby.h"\
!IF "$(CFG)" == "duel - Win32 Release"
"$(INTDIR)\lobby.obj" : $(SOURCE) $(DEP_CPP_LOBBY) "$(INTDIR)"
!ELSEIF "$(CFG)" == "duel - Win32 Debug"
"$(INTDIR)\lobby.obj" : $(SOURCE) $(DEP_CPP_LOBBY) "$(INTDIR)"
"$(INTDIR)\lobby.sbr" : $(SOURCE) $(DEP_CPP_LOBBY) "$(INTDIR)"
!ENDIF
# End Source File
################################################################################
# Begin Source File
SOURCE=.\lobby.h
!IF "$(CFG)" == "duel - Win32 Release"
!ELSEIF "$(CFG)" == "duel - Win32 Debug"
!ENDIF
# End Source File
################################################################################
# Begin Source File
SOURCE=.\resource.h
!IF "$(CFG)" == "duel - Win32 Release"
!ELSEIF "$(CFG)" == "duel - Win32 Debug"
!ENDIF
# End Source File
################################################################################
# Begin Source File
SOURCE=.\util.cpp
DEP_CPP_UTIL_=\
".\duel.h"\
!IF "$(CFG)" == "duel - Win32 Release"
"$(INTDIR)\util.obj" : $(SOURCE) $(DEP_CPP_UTIL_) "$(INTDIR)"
!ELSEIF "$(CFG)" == "duel - Win32 Debug"
"$(INTDIR)\util.obj" : $(SOURCE) $(DEP_CPP_UTIL_) "$(INTDIR)"
"$(INTDIR)\util.sbr" : $(SOURCE) $(DEP_CPP_UTIL_) "$(INTDIR)"
!ENDIF
# End Source File
################################################################################
# Begin Source File
SOURCE=.\wizard.cpp
DEP_CPP_WIZAR=\
".\dputil.h"\
".\duel.h"\
".\gameproc.h"\
".\lobby.h"\
".\wizard.h"\
{$(INCLUDE)}"\dplobby.h"\
!IF "$(CFG)" == "duel - Win32 Release"
"$(INTDIR)\wizard.obj" : $(SOURCE) $(DEP_CPP_WIZAR) "$(INTDIR)"
!ELSEIF "$(CFG)" == "duel - Win32 Debug"
"$(INTDIR)\wizard.obj" : $(SOURCE) $(DEP_CPP_WIZAR) "$(INTDIR)"
"$(INTDIR)\wizard.sbr" : $(SOURCE) $(DEP_CPP_WIZAR) "$(INTDIR)"
!ENDIF
# End Source File
################################################################################
# Begin Source File
SOURCE=.\ddutil.cpp
DEP_CPP_DDUTI=\
".\ddutil.h"\
!IF "$(CFG)" == "duel - Win32 Release"
"$(INTDIR)\ddutil.obj" : $(SOURCE) $(DEP_CPP_DDUTI) "$(INTDIR)"
!ELSEIF "$(CFG)" == "duel - Win32 Debug"
"$(INTDIR)\ddutil.obj" : $(SOURCE) $(DEP_CPP_DDUTI) "$(INTDIR)"
"$(INTDIR)\ddutil.sbr" : $(SOURCE) $(DEP_CPP_DDUTI) "$(INTDIR)"
!ENDIF
# End Source File
# End Target
# End Project
################################################################################

Binary file not shown.

View File

@@ -0,0 +1,272 @@
//Microsoft Developer Studio generated resource script.
//
#include "resource.h"
#define APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 2 resource.
//
#include "afxres.h"
/////////////////////////////////////////////////////////////////////////////
#undef APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
// English (U.S.) resources
#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
#ifdef _WIN32
LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
#pragma code_page(1252)
#endif //_WIN32
#ifdef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// TEXTINCLUDE
//
1 TEXTINCLUDE DISCARDABLE
BEGIN
"resource.h\0"
END
2 TEXTINCLUDE DISCARDABLE
BEGIN
"#include ""afxres.h""\r\n"
" \0"
END
3 TEXTINCLUDE DISCARDABLE
BEGIN
"\r\n"
"\0"
END
#endif // APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// Dialog
//
IDD_CONNECT_STATUS DIALOG DISCARDABLE 120, 110, 162, 52
STYLE DS_MODALFRAME | WS_POPUP | WS_VISIBLE | WS_CAPTION
CAPTION "Duel Connection Status"
FONT 8, "MS Shell Dlg"
BEGIN
CTEXT "Finding game...",IDC_DUEL_STATUSTEXT,7,7,141,13
DEFPUSHBUTTON "&Cancel",IDC_LOBBYCONNECTCANCEL,52,29,51,14
END
IDD_MULTIPLAYER_GAMES DIALOG DISCARDABLE 0, 0, 282, 140
STYLE DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU
CAPTION "Multiplayer Games"
FONT 8, "MS Shell Dlg"
BEGIN
LTEXT "Select Game To Join:",-1,7,15,69,8
LISTBOX IDC_GAMES_LIST,7,24,268,91,LBS_SORT |
LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP
PUSHBUTTON "Join",IDC_JOIN,7,119,50,14
DEFPUSHBUTTON "Create",IDC_CREATE,61,119,50,14
PUSHBUTTON "Cancel",IDC_BACK,225,119,50,14
CONTROL "Start Search",IDC_SEARCH_CHECK,"Button",BS_AUTOCHECKBOX |
BS_PUSHLIKE | WS_TABSTOP,220,7,55,14
END
IDD_MULTIPLAYER_CONNECT DIALOG DISCARDABLE 0, 0, 282, 151
STYLE DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU
CAPTION "Multiplayer Connect"
FONT 8, "MS Shell Dlg"
BEGIN
LTEXT "Player Name:",IDC_STATIC,7,10,43,8
EDITTEXT IDC_PLAYER_NAME_EDIT,7,22,268,14,ES_AUTOHSCROLL
LTEXT "Connection Type:",IDC_STATIC,7,41,57,8
LISTBOX IDC_CONNECTION_LIST,7,53,268,72,LBS_SORT |
LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP
DEFPUSHBUTTON "OK",IDOK,171,130,50,14
PUSHBUTTON "Cancel",IDCANCEL,225,130,50,14
END
IDD_MULTIPLAYER_CREATE DIALOG DISCARDABLE 0, 0, 186, 77
STYLE DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU
CAPTION "Create Game"
FONT 8, "MS Shell Dlg"
BEGIN
EDITTEXT IDC_EDIT_SESSION_NAME,7,19,172,14,ES_AUTOHSCROLL
CONTROL "Use DirectPlay Protocol",IDC_CHECK_DPLAY_PROTOCOL,
"Button",BS_AUTOCHECKBOX | WS_TABSTOP,49,40,91,10
DEFPUSHBUTTON "OK",IDOK,7,56,50,14
PUSHBUTTON "Cancel",IDCANCEL,129,56,50,14
LTEXT "Game Name:",IDC_STATIC,7,7,42,8
END
IDD_LOBBY_WAIT_STATUS DIALOG DISCARDABLE 120, 110, 162, 52
STYLE DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_VISIBLE | WS_CAPTION
CAPTION "Lobby Connection Status"
FONT 8, "MS Shell Dlg"
BEGIN
DEFPUSHBUTTON "&Cancel",IDC_LOBBYCONNECTCANCEL,55,31,51,14
CTEXT "Finding Game...",IDC_WAIT_TEXT,7,14,141,8
END
/////////////////////////////////////////////////////////////////////////////
//
// Bitmap
//
SPLASH BITMAP MOVEABLE PURE "SPLASH.BMP"
DUEL8 BITMAP MOVEABLE PURE "DUEL.BMP"
/////////////////////////////////////////////////////////////////////////////
//
// Icon
//
// Icon with lowest ID value placed first to ensure application icon
// remains consistent on all systems.
IDI_MAIN ICON DISCARDABLE "duel.ico"
/////////////////////////////////////////////////////////////////////////////
//
// WAVE
//
SBOUNCE WAVE DISCARDABLE "Sbounce.wav"
LBOOM WAVE DISCARDABLE "Lboom.wav"
SBOOM WAVE DISCARDABLE "Sboom.wav"
BFIRE WAVE DISCARDABLE "Bfire.wav"
SENGINE WAVE DISCARDABLE "Sengine.wav"
SSTART WAVE DISCARDABLE "Sstart.wav"
SSTOP WAVE DISCARDABLE "Sstop.wav"
/////////////////////////////////////////////////////////////////////////////
//
// DESIGNINFO
//
#ifdef APSTUDIO_INVOKED
GUIDELINES DESIGNINFO DISCARDABLE
BEGIN
IDD_CONNECT_STATUS, DIALOG
BEGIN
LEFTMARGIN, 7
RIGHTMARGIN, 148
TOPMARGIN, 7
BOTTOMMARGIN, 24
END
IDD_MULTIPLAYER_CREATE, DIALOG
BEGIN
LEFTMARGIN, 7
RIGHTMARGIN, 179
VERTGUIDE, 94
TOPMARGIN, 7
BOTTOMMARGIN, 70
END
IDD_LOBBY_WAIT_STATUS, DIALOG
BEGIN
LEFTMARGIN, 7
RIGHTMARGIN, 148
TOPMARGIN, 7
BOTTOMMARGIN, 45
END
END
#endif // APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// String Table
//
STRINGTABLE DISCARDABLE
BEGIN
IDS_WIZARD_FONTNAME "Times"
IDS_WIZARD_TITLE "Duel Setup"
IDS_WIZARD_TITLE_SP "Communications Channel (Step 2 of 3)"
IDS_WIZARD_TITLE_GS "Game Setup (Step 1 of 3)"
IDS_WIZARD_TITLE_JS "Join Session (Step 3 of 3)"
IDS_WIZARD_TITLE_HS "Host Session (Step 3 of 3)"
IDS_DUEL_HELP "Spacebar\t\t- Fire\nRight Arrow\t- Rotate right\nLeft Arrow\t- Rotate left\nUp Arrow\t\t- Forward\nDown Arrow\t- Backward\nNumPad 5\t- Stop\nA\t\t- Asynchronous Messaging\nR\t\t- Reliable Messaging\nF1\t\t- Help\nF5\t\t- Frames/sec\nESC or F12\t- Quit\n"
END
STRINGTABLE DISCARDABLE
BEGIN
IDS_DDRAW_ERROR_DDC "DirectDraw create failed"
IDS_DDRAW_ERROR_SCL "SetCooperativeLevel failed"
IDS_DDRAW_ERROR_SDM "SetDisplayMode failed"
IDS_DDRAW_ERROR_CREATESURFACE "IDirectDraw::CreateSurface() failed"
IDS_DDRAW_ERROR_GAS "Backbuffer couldn't be obtained"
IDS_DDRAW_ERROR_CC "CreateClipper failed"
IDS_DDRAW_ERROR_SH "Clipper SetHwnd failed"
IDS_DDRAW_ERROR_SC "Clipper object couldn't be attached to the front buffer"
IDS_DDRAW_ERROR_RS "Surfaces couldn't be restored"
END
STRINGTABLE DISCARDABLE
BEGIN
IDS_DINPUT_ERROR_DIC "DirectInputCreate failed"
IDS_DINPUT_ERROR_ED "Enum keyboard devices failed"
IDS_DINPUT_ERROR_CD "Create keyboard device failed"
IDS_DINPUT_ERROR_SP "Set non-exclusive mode failed"
IDS_DINPUT_ERROR_A "Keyboard acquire failed"
IDS_DINPUT_ERROR_DF "Set keyboard data format failed"
IDS_DDUTIL_ERROR_LI "LoadImage failed. Handle is NULL."
IDS_DDUTIL_ERROR_DDCB "DDUtil_CopyBitmap failed"
IDS_DDUTIL_ERROR_CCDC "CreateCompatibleDC failed"
IDS_DSOUND_LOADWAVES "Could not load WAVE resource."
IDS_DSOUND_DUPBUF "Could not duplicate a sound buffer for new ship"
END
STRINGTABLE DISCARDABLE
BEGIN
IDS_DPLAY_ERROR_CP "Player create failed"
IDS_DPLAY_ERROR_JS "Session join failed"
IDS_DPLAY_ERROR_CS "Session create failed"
IDS_DPLAY_ERROR_IDC "DirectPlay object create failed"
IDS_DPLAY_ERROR_SL "You have been disconnected from the session"
IDS_DPLAY_ERROR_GPLD "Get player local data failed"
IDS_DPLAY_ERROR_SPLD "Set player local data failed"
IDS_DPLAY_ERROR_GPRD "Get player remote data failed"
IDS_DPLAY_ERROR_SPRD "Set player remote data failed"
IDS_DPLAY_ERROR_GSD "Get session description failed"
IDS_DPLAY_ERROR_EP "Enumerate players failed"
IDS_DPLAY_ERROR_ES "Enumerate sessions failed"
IDS_DPLAY_ERROR_C "DirectPlay Close failed"
IDS_DPLAY_ERROR_R "DirectPlay Release failed"
IDS_DPLAY_ERROR_DP "Destroy player failed"
IDS_DPLAY_ERROR_CLSID "This application requires DirectPlay 6 or later"
END
STRINGTABLE DISCARDABLE
BEGIN
IDS_DPLOBBY_ERROR_R "DirectPlayLobby Release failed"
IDS_DPLOBBY_ERROR_GCS "DirectPlayLobby GetConnectionSettings failed"
IDS_DPLOBBY_ERROR_SCS "DirectPlayLobby SetConnectionSettings failed"
IDS_DPLOBBY_ERROR_C "DirectPlayLobby Create failed"
IDS_DPLOBBY_ERROR_CONNECT "DirectPlayLobby Connect failed"
IDS_WIZARD_ERROR_GSG "Session guid couldn't be obtained from the parent item"
IDS_WIN_ERROR "Windows API failure"
END
#endif // English (U.S.) resources
/////////////////////////////////////////////////////////////////////////////
#ifndef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 3 resource.
//
/////////////////////////////////////////////////////////////////////////////
#endif // not APSTUDIO_INVOKED

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,221 @@
//-----------------------------------------------------------------------------
// File: GameProc.h
//
// Desc: Game processing routines
//
// Copyright (C) 1995-2001 Microsoft Corporation. All Rights Reserved.
//-----------------------------------------------------------------------------
#define IDIRECTPLAY2_OR_GREATER
#include <ddraw.h>
#include <dplay.h>
#include <dsound.h>
// align on single byte boundaries
// this is a stop-gap measure until the structures can be re-arranged.
#pragma pack(1)
#define MAX_SHIP_X (MAX_SCREEN_X - 32)
#define MAX_SHIP_Y (MAX_SCREEN_Y - 32)
#define MAX_SHIP_FRAME 40
#define MAX_BULLET_X (MAX_SCREEN_X - 3)
#define MAX_BULLET_Y (MAX_SCREEN_Y - 3)
#define MAX_BULLET_FRAME 400
#define NUM_SHIP_TYPES 4
#define DEF_SHOW_DELAY (2000)
#define MAX_BUFFER_SIZE 256
#define UPDATE_INTERVAL 40 // interval between position updates in milliseconds (25 FPS)
#define SYNC_INTERVAL 1000 // synchronize once every second
#define HIDE_TIMEOUT 5000 // time for which a ship is disabled after a hit
// Keyboard commands
#define KEY_STOP 0x00000001l
#define KEY_DOWN 0x00000002l
#define KEY_LEFT 0x00000004l
#define KEY_RIGHT 0x00000008l
#define KEY_UP 0x00000010l
#define KEY_FIRE 0x00000020l
#define KEY_ENGINEOFF 0x00000040l
// Offsets for the bullet bitmap
#define BULLET_X 304
#define BULLET_Y 0
struct FRAG
{
double dPosX;
double dPosY;
LPDIRECTDRAWSURFACE pdds;
RECT src;
double dVelX;
double dVelY;
BOOL valid;
};
struct SHIP
{
double dPosX, dPosY; // ship x and y position
double dBulletPosX, dBulletPosY; // bullet x and y position
DWORD dwBulletFrame; // bullet frame
char cFrame; // current ship frame
BYTE byType; // ship type
BOOL bEnable; // is this ship active?
BOOL bBulletEnable; // Is there an active bullet?
double dVelX, dVelY; // ship x and y velocity (pixels/millisecond)
double dBulletVelX, dBulletVelY; // bullet x and y velocity (pixels/millisecond)
DWORD dwScore; // current score
DWORD dwLastTick; // most recent time stamp
BOOL bIgnore; // flag used to synchronize ship explosions
int iCountDown; // enable time-out
DWORD dwFrameCount; // number of frames since beginning of time
// DSound members
DWORD dwKeys; // the keyboard state
BOOL bEngineRunning; // These BOOLs keep track of the ship's
BOOL bMoving; // last condition so we can play sounds
BOOL bBounced; // when they change
BOOL bBlockHit;
BOOL bDeath;
BOOL bFiring;
};
struct BLOCKS
{
BYTE bits[30][5];
};
//-----------------------------------------------------------------------------
// communication packet structures
//-----------------------------------------------------------------------------
#define MSG_HOST 0x11 // message containing field layout, sent by host
#define MSG_BLOCKHIT 0x22 // block hit message
#define MSG_SHIPHIT 0x33 // ship hit message
#define MSG_ADDBLOCK 0x44 // add block message
#define MSG_CONTROL 0x55 // game keys message
#define MSG_SYNC 0x66 // synchronization message containing the rendezvous location
struct GENERICMSG
{
BYTE byType;
};
struct OLDHOSTMSG
{
BYTE byType;
BLOCKS Blocks;
};
struct HOSTMSG
{
BYTE byType;
BLOCKS Blocks;
int usedShipTypes[NUM_SHIP_TYPES];
};
struct BLOCKHITMSG
{
BYTE byType;
BYTE byRow;
BYTE byCol;
BYTE byMask;
};
struct SHIPHITMSG
{
BYTE byType;
DPID Id;
};
struct ADDBLOCKMSG
{
BYTE byType;
BYTE byX;
BYTE byY;
};
struct CONTROLMSG
{
BYTE byType;
BYTE byState;
};
struct SYNCMSG
{
BYTE byType;
BYTE byShipType; // this is needed only when sends are unreliable
char cFrame;
double dPosX;
double dPosY;
};
//-----------------------------------------------------------------------------
// Prototypes
//-----------------------------------------------------------------------------
VOID LaunchGame();
VOID ExitGame();
HRESULT InitOurShip();
HRESULT InitLocalSoundData();
BOOL WINAPI SetPlayerLocalSoundDataCB( DPID dpId, DWORD dwPlayerType,
LPCDPNAME pName, DWORD dwFlags,
VOID* pContext );
VOID ReleaseLocalData();
VOID ReleasePlayerLocalSoundData( SHIP* pShip );
BOOL WINAPI ReleasePlayerLocalDataCB( DPID dpId, DWORD dwPlayerType,
LPCDPNAME pName, DWORD dwFlags,
VOID* pContext );
VOID UpdateState( SHIP* pShip, DWORD dwControls );
VOID SendSync( SHIP* pShip );
VOID UpdateDisplayStatus( SHIP* pShip );
VOID UpdatePosition( DPID dpId, SHIP* ship );
BOOL IsHit( int x, int y );
VOID InitField();
BOOL setBlock( int x, int y );
VOID AddFrag( SHIP* pShip, int offX, int offY );
VOID UpdateFragment( int i );
VOID DestroyShip( SHIP* pShip );
VOID DestroyGame();
BOOL UpdateFrame();
VOID ProcessSoundFlags( SHIP* pShip );
BOOL WINAPI RenderPlayerCB( DPID dpId, DWORD dwPlayerType, LPCDPNAME pName,
DWORD dwFlags, VOID* pContext );
BOOL DrawScreen();
BOOL DrawScore();
VOID DrawShip( SHIP* pShip );
VOID DrawBlock( int x, int y );
VOID DrawBullet( SHIP* pShip );
VOID DrawFragments();
VOID DisplayFrameRate();
VOID GetConnection();
HRESULT ReceiveMessages();
VOID DoSystemMessage( DPMSG_GENERIC* pMsg, DWORD dwMsgSize, DPID idFrom,
DPID idTo );
VOID DoApplicationMessage( GENERICMSG* pMsg, DWORD dwMsgSize, DPID idFrom,
DPID idTo );
VOID SendGameMessage( GENERICMSG* pMsg, DPID idTo );
VOID CleanupComm();
HRESULT InitializeGameSounds();
VOID CleanupGameSounds();
// restore default alignment
#pragma pack()

View File

@@ -0,0 +1,534 @@
//-----------------------------------------------------------------------------
// File: gfx.cpp
//
// Desc: Graphics routines
//
// Copyright (C) 1995-2001 Microsoft Corporation. All Rights Reserved.
//-----------------------------------------------------------------------------
#include "duel.h"
#include "gfx.h"
#include "diutil.h"
#include "ddutil.h"
//-----------------------------------------------------------------------------
// Globals
//-----------------------------------------------------------------------------
extern BOOL g_bFullscreen; // Window or fullscreen mode ?
extern HWND g_hwndMain; // Main window
extern DWORD g_dwKeys;
extern int g_nProgramState; // Current state of program
extern RECT g_rcWindow; // Client window rectangle
extern HINSTANCE g_hInst; // Application instance handle
LPDIRECTDRAW g_pDD = NULL; // DirectDraw interface
LPDIRECTDRAWPALETTE g_pArtPalette = NULL; // Game screen palette
LPDIRECTDRAWPALETTE g_pSplashPalette = NULL; // Splash screen palette
LPDIRECTDRAWSURFACE g_pddsFrontBuffer = NULL; // primary surface
LPDIRECTDRAWSURFACE g_pddsBackBuffer = NULL; // back buffer for animation
LPDIRECTDRAWSURFACE g_pddsShip[4]; // ship bitmaps
LPDIRECTDRAWSURFACE g_pddsNumbers; // Numbers bitmap
DWORD g_dwFillColor;
//-----------------------------------------------------------------------------
// Name: InitGraphics()
// Desc:
//-----------------------------------------------------------------------------
HRESULT InitGraphics()
{
DDCAPS ddcaps;
HRESULT hr;
DDSURFACEDESC ddsd;
DDSCAPS ddscaps;
// Create a window
g_hwndMain = CreateWindowEx( WS_EX_APPWINDOW, TEXT("DuelClass"),
TEXT("Duel"), WS_POPUP | WS_SYSMENU, 0, 0,
GetSystemMetrics(SM_CXSCREEN),
GetSystemMetrics(SM_CYSCREEN),
NULL, NULL, g_hInst, NULL );
if( NULL == g_hwndMain )
return E_FAIL;
UpdateWindow( g_hwndMain );
SetFocus( g_hwndMain );
// DDraw stuff begins here
if( FAILED( hr = DirectDrawCreate( NULL, &g_pDD, NULL ) ) )
{
ShowError(IDS_DDRAW_ERROR_DDC);
return E_FAIL;
}
// Set access mode based on fullscreen/window
if( g_bFullscreen )
{
hr = g_pDD->SetCooperativeLevel( g_hwndMain,
DDSCL_EXCLUSIVE | DDSCL_FULLSCREEN );
}
else
{
hr = g_pDD->SetCooperativeLevel( g_hwndMain,
DDSCL_NORMAL);
}
if( FAILED(hr) )
{
ShowError(IDS_DDRAW_ERROR_SCL);
return E_FAIL;
}
if( g_bFullscreen )
{
// Set the mode to 640 by 480 by 8
if( FAILED( g_pDD->SetDisplayMode( 640, 480, 8 ) ) )
{
ShowError(IDS_DDRAW_ERROR_SDM);
return E_FAIL;
}
}
else
{
RECT rcWork;
RECT rc;
DWORD dwStyle;
// If we are still a WS_POPUP window we should convert to a
// normal app window so we look like a windows app.
dwStyle = GetWindowStyle(g_hwndMain);
dwStyle &= ~WS_POPUP;
dwStyle |= WS_OVERLAPPED | WS_CAPTION | WS_THICKFRAME | WS_MINIMIZEBOX;
SetWindowLong( g_hwndMain, GWL_STYLE, dwStyle );
// Aet window size
SetRect( &rc, 0, 0, MAX_DEFWIN_X, MAX_DEFWIN_Y );
AdjustWindowRectEx( &rc, GetWindowStyle(g_hwndMain),
GetMenu(g_hwndMain) != NULL,
GetWindowExStyle(g_hwndMain) );
SetWindowPos( g_hwndMain, NULL, 0, 0, rc.right-rc.left,
rc.bottom-rc.top,
SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE);
SetWindowPos( g_hwndMain, HWND_NOTOPMOST, 0, 0, 0, 0,
SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE);
// Make sure our window does not hang outside of the work area
SystemParametersInfo( SPI_GETWORKAREA, 0, &rcWork, 0 );
GetWindowRect( g_hwndMain, &rc );
if( rc.left < rcWork.left ) rc.left = rcWork.left;
if( rc.top < rcWork.top ) rc.top = rcWork.top;
SetWindowPos( g_hwndMain, NULL, rc.left, rc.top, 0, 0,
SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE );
}
// Check the color key hardware capabilities
ddcaps.dwSize = sizeof( ddcaps );
memset( &ddsd, 0, sizeof( ddsd ) );
ddsd.dwSize = sizeof( ddsd );
if( g_bFullscreen )
{
// Create surfaces
ddsd.dwFlags = DDSD_CAPS | DDSD_BACKBUFFERCOUNT;
ddsd.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE |
DDSCAPS_FLIP |
DDSCAPS_COMPLEX;
ddsd.dwBackBufferCount = 1;
if( FAILED( hr = g_pDD->CreateSurface( &ddsd, &g_pddsFrontBuffer,
NULL ) ) )
{
ShowError(IDS_DDRAW_ERROR_CREATESURFACE);
return E_FAIL;
}
// Get a pointer to the back buffer
ddscaps.dwCaps = DDSCAPS_BACKBUFFER;
if( FAILED( hr = g_pddsFrontBuffer->GetAttachedSurface( &ddscaps,
&g_pddsBackBuffer ) ) )
{
ShowError(IDS_DDRAW_ERROR_GAS);
return E_FAIL;
}
}
else
{
LPDIRECTDRAWCLIPPER pcClipper;
// Window case, create the primary surface
// and create a backbuffer in offscreen memory
ddsd.dwFlags = DDSD_CAPS;
ddsd.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE;
if( FAILED( g_pDD->CreateSurface( &ddsd, &g_pddsFrontBuffer, NULL ) ) )
{
ShowError(IDS_DDRAW_ERROR_CREATESURFACE);
return E_FAIL;
}
ddsd.dwFlags = DDSD_CAPS | DDSD_WIDTH | DDSD_HEIGHT;
ddsd.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN;
ddsd.dwWidth = MAX_DEFWIN_X;
ddsd.dwHeight = MAX_DEFWIN_Y;
if( FAILED( hr = g_pDD->CreateSurface( &ddsd, &g_pddsBackBuffer, NULL ) ) )
{
ShowError(IDS_DDRAW_ERROR_CREATESURFACE);
return E_FAIL;
}
if( FAILED( hr = g_pDD->CreateClipper( 0, &pcClipper, NULL) ) )
{
ShowError(IDS_DDRAW_ERROR_CC);
return E_FAIL;
}
if( FAILED( hr = pcClipper->SetHWnd( 0, g_hwndMain) ) )
{
pcClipper->Release();
ShowError(IDS_DDRAW_ERROR_SH);
return E_FAIL;
}
if( FAILED( hr = g_pddsFrontBuffer->SetClipper( pcClipper) ) )
{
pcClipper->Release();
ShowError(IDS_DDRAW_ERROR_SC);
return E_FAIL;
}
// Done with clipper
pcClipper->Release();
}
ddsd.dwFlags = DDSD_CAPS | DDSD_WIDTH | DDSD_HEIGHT;
ddsd.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN;
ddsd.dwWidth = 320;
ddsd.dwHeight = 128;
for( DWORD i=0; i<4; i++ )
{
if( FAILED( hr = g_pDD->CreateSurface( &ddsd, &g_pddsShip[i], NULL ) ) )
{
ShowError(IDS_DDRAW_ERROR_CREATESURFACE);
return E_FAIL;
}
}
ddsd.dwHeight = 16;
if( FAILED( hr = g_pDD->CreateSurface( &ddsd, &g_pddsNumbers, NULL ) ) )
{
ShowError(IDS_DDRAW_ERROR_CREATESURFACE);
return E_FAIL;
}
if( FAILED( RestoreSurfaces() ) )
{
ShowError(IDS_DDRAW_ERROR_RS);
return E_FAIL;
}
g_dwKeys = 0;
ShowWindow( g_hwndMain, SW_SHOW);
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: CleanupGraphics()
// Desc:
//-----------------------------------------------------------------------------
VOID CleanupGraphics()
{
for( DWORD i=0; i<4; i++ )
if( g_pddsShip[i] )
g_pddsShip[i]->Release();
if( g_pddsNumbers )
g_pddsNumbers->Release();
if( g_pddsFrontBuffer )
g_pddsFrontBuffer->Release();
if( g_pArtPalette )
g_pArtPalette->Release();
if( g_pSplashPalette )
g_pSplashPalette->Release();
if( !g_bFullscreen && g_pddsBackBuffer )
g_pddsBackBuffer->Release();
if( g_pDD )
g_pDD->Release();
}
//-----------------------------------------------------------------------------
// Name: BltSplashScreen()
// Desc:
//-----------------------------------------------------------------------------
HRESULT BltSplashScreen( RECT* prc )
{
HRESULT hr;
HBITMAP hbm;
if( ( g_pddsFrontBuffer == NULL ) || ( g_pSplashPalette == NULL ) ||
( g_pddsBackBuffer == NULL ) )
return E_FAIL;
// Set the palette before loading the splash screen
g_pddsFrontBuffer->SetPalette( g_pSplashPalette );
hbm = (HBITMAP)LoadImage( GetModuleHandle( NULL ), TEXT("SPLASH"),
IMAGE_BITMAP, 0, 0, LR_CREATEDIBSECTION );
if( NULL == hbm )
return E_FAIL;
// If the surface is lost, DDUtil_CopyBitmap will fail and the surface will
// be restored below.
hr = DDUtil_CopyBitmap( g_pddsBackBuffer, hbm, 0, 0, 0, 0 );
DeleteObject( hbm );
while( 1 )
{
hr = g_pddsFrontBuffer->Blt( &g_rcWindow, g_pddsBackBuffer,
prc, DDBLT_WAIT, NULL);
if( SUCCEEDED(hr) )
return S_OK;
if( hr == DDERR_SURFACELOST )
if( FAILED( RestoreSurfaces() ) )
return E_FAIL;
if( hr != DDERR_WASSTILLDRAWING )
return E_FAIL;
}
}
//-----------------------------------------------------------------------------
// Name: BltNumber()
// Desc:
//-----------------------------------------------------------------------------
HRESULT BltNumber( CHAR* strScore, int x, int y )
{
while( *strScore )
{
RECT src;
src.left = ((*strScore++)-'0')*16;
src.top = 0;
src.right = src.left + 16;
src.bottom = src.top + 16;
BltObject( x, y, g_pddsNumbers, &src, DDBLTFAST_SRCCOLORKEY );
x += 16;
}
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: BltObject()
// Desc:
//-----------------------------------------------------------------------------
HRESULT BltObject( int x, int y, LPDIRECTDRAWSURFACE pdds, RECT* prc,
DWORD flags )
{
if( NULL == pdds )
return E_FAIL;
while( 1 )
{
HRESULT hr = g_pddsBackBuffer->BltFast( x, y, pdds, prc, flags );
if( FAILED(hr) )
{
if( hr == DDERR_WASSTILLDRAWING )
continue;
if( hr == DDERR_SURFACELOST )
if( SUCCEEDED( RestoreSurfaces() ) )
continue;
return E_FAIL;
}
return S_OK;
}
}
//-----------------------------------------------------------------------------
// Name: EraseScreen()
// Desc:
//-----------------------------------------------------------------------------
VOID EraseScreen()
{
// Erase the background
DDBLTFX ddbltfx;
ZeroMemory( &ddbltfx, sizeof(ddbltfx) );
ddbltfx.dwSize = sizeof(ddbltfx);
#ifdef NONAMELESSUNION
ddbltfx.u5.dwFillColor = g_dwFillColor;
#else
ddbltfx.dwFillColor = g_dwFillColor;
#endif
while( 1 )
{
HRESULT hr = g_pddsBackBuffer->Blt( NULL, NULL, NULL,
DDBLT_COLORFILL, &ddbltfx );
if( SUCCEEDED(hr) )
return;
if( hr == DDERR_SURFACELOST )
{
if( FAILED( RestoreSurfaces() ) )
return;
}
if( hr != DDERR_WASSTILLDRAWING )
return;
}
}
//-----------------------------------------------------------------------------
// Name: FlipScreen()
// Desc:
//-----------------------------------------------------------------------------
VOID FlipScreen()
{
// Flip the surfaces
if( g_bFullscreen )
{
while( 1 )
{
HRESULT hr = g_pddsFrontBuffer->Flip( NULL, 0 );
if( hr == DDERR_SURFACELOST )
{
if( FAILED( RestoreSurfaces() ) )
return;
}
if( hr != DDERR_WASSTILLDRAWING )
return;
}
}
else
{
g_pddsFrontBuffer->Blt( &g_rcWindow, g_pddsBackBuffer, NULL,
DDBLT_WAIT, NULL );
}
}
//-----------------------------------------------------------------------------
// Name: RestoreSurfaces()
// Desc:
//-----------------------------------------------------------------------------
HRESULT RestoreSurfaces()
{
HRESULT hr;
HBITMAP hbm;
if( FAILED( hr = g_pddsFrontBuffer->Restore() ) )
return hr;
if( FAILED( hr = g_pddsBackBuffer->Restore() ) )
return hr;
for( DWORD i=0; i<4; i++ )
if( FAILED( hr = g_pddsShip[i]->Restore() ) )
return hr;
// Create and set the palette for the splash bitmap
g_pSplashPalette = DDUtil_LoadPalette( g_pDD, TEXT("SPLASH") );
if( NULL == g_pSplashPalette )
return E_FAIL;
// Create and set the palette for the art bitmap
g_pArtPalette = DDUtil_LoadPalette( g_pDD, TEXT("Duel8") );
if( NULL == g_pArtPalette )
return E_FAIL;
// set the palette before loading the art
g_pddsFrontBuffer->SetPalette( g_pArtPalette );
hbm = (HBITMAP)LoadImage( GetModuleHandle(NULL), TEXT("Duel8"),
IMAGE_BITMAP, 0, 0, LR_CREATEDIBSECTION );
if( NULL == hbm )
return E_FAIL;
if( FAILED( hr = DDUtil_CopyBitmap( g_pddsShip[0], hbm, 0, 0, 320, 128 ) ) )
{
DeleteObject( hbm );
return E_FAIL;
}
if( FAILED( hr = DDUtil_CopyBitmap( g_pddsShip[1], hbm, 0, 128, 320, 128 ) ) )
{
DeleteObject( hbm );
return E_FAIL;
}
if( FAILED( hr = DDUtil_CopyBitmap( g_pddsShip[2], hbm, 0, 256, 320, 128 ) ) )
{
DeleteObject( hbm );
return E_FAIL;
}
if( FAILED( hr = DDUtil_CopyBitmap( g_pddsShip[3], hbm, 0, 384, 320, 128 ) ) )
{
DeleteObject( hbm );
return E_FAIL;
}
if( FAILED( hr = DDUtil_CopyBitmap( g_pddsNumbers, hbm, 0, 512, 320, 16 ) ) )
{
DeleteObject( hbm );
return E_FAIL;
}
DeleteObject( hbm );
// set colorfill colors and colorkeys according to bitmap contents
g_dwFillColor = DDUtil_ColorMatch( g_pddsShip[0], CLR_INVALID );
DDUtil_SetColorKey( g_pddsShip[0], CLR_INVALID );
DDUtil_SetColorKey( g_pddsShip[1], CLR_INVALID );
DDUtil_SetColorKey( g_pddsShip[2], CLR_INVALID );
DDUtil_SetColorKey( g_pddsShip[3], CLR_INVALID );
DDUtil_SetColorKey( g_pddsNumbers, CLR_INVALID );
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: SetGamePalette()
// Desc:
//-----------------------------------------------------------------------------
VOID SetGamePalette()
{
if( g_pddsFrontBuffer )
g_pddsFrontBuffer->SetPalette( g_pArtPalette );
}

View File

@@ -0,0 +1,22 @@
//-----------------------------------------------------------------------------
// File: gfx.h
//
// Desc: Graphics routines
//
// Copyright (C) 1995-2001 Microsoft Corporation. All Rights Reserved.
//-----------------------------------------------------------------------------
#include "ddraw.h"
HRESULT InitGraphics();
VOID CleanupGraphics();
HRESULT BltSplashScreen( RECT* prc );
HRESULT BltNumber( CHAR* strScore, int x, int y );
HRESULT BltObject( int x, int y, LPDIRECTDRAWSURFACE pdds, RECT* src,
DWORD dwFlags );
VOID EraseScreen();
VOID FlipScreen();
HRESULT RestoreSurfaces();
VOID SetGamePalette();

Binary file not shown.

View File

@@ -0,0 +1,240 @@
//-----------------------------------------------------------------------------
// File: Lobby.cpp
//
// Desc: DP lobby related routines
//
// Copyright (C) 1995-2001 Microsoft Corporation. All Rights Reserved.
//-----------------------------------------------------------------------------
#include "duel.h"
#include "lobby.h"
//-----------------------------------------------------------------------------
// Definitions
//-----------------------------------------------------------------------------
#define SAFE_DELETE(p) { if(p) { delete (p); (p)=NULL; } }
#define SAFE_DELETE_ARRAY(p) { if(p) { delete[] (p); (p)=NULL; } }
#define SAFE_RELEASE(p) { if(p) { (p)->Release(); (p)=NULL; } }
#define TIMERID 1 // Timer ID to use
#define TIMERINTERVAL 250 // Timer interval
//-----------------------------------------------------------------------------
// Globals
//-----------------------------------------------------------------------------
extern LPDIRECTPLAY4 g_pDP; // DirectPlay object pointer
extern LPDPLCONNECTION g_pDPLConnection; // Connection settings
extern LPDIRECTPLAYLOBBY3 g_pDPLobby; // Lobby object pointer
extern BOOL g_bHostPlayer; // Flag indicating if we are hosting
extern HWND g_hwndMain; // Main application window handle
extern HINSTANCE g_hInst; // Application instance handle
BOOL g_bLobbyMsgSupported; // Lobby messages are supported
GUID g_guidPlayer; // This player in this session
//-----------------------------------------------------------------------------
// Name: DPLobbyRelease()
// Desc: Wrapper for DirectPlayLobby Release API
//-----------------------------------------------------------------------------
HRESULT DPLobbyRelease()
{
// Cleanup lobby
SAFE_DELETE_ARRAY( g_pDPLConnection );
SAFE_RELEASE( g_pDPLobby );
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: DoingLobbyMessages()
// Desc: Return TRUE if connected to a lobby and messages are supported.
//-----------------------------------------------------------------------------
BOOL DoingLobbyMessages()
{
return( g_pDPLobby && g_bLobbyMsgSupported );
}
//-----------------------------------------------------------------------------
// Name: LobbyMessageInit()
// Desc: Initialize lobby message processing. Must be done while a lobby
// connection is open.
//-----------------------------------------------------------------------------
HRESULT LobbyMessageInit()
{
if( NULL ==g_pDPLobby ) // Not connected to a lobby
return E_FAIL;
g_bLobbyMsgSupported = FALSE; // Until we find out otherwise.
// Find out if lobby messages are supported by the lobby
DPLMSG_GETPROPERTY msgGetProp;
ZeroMemory( &msgGetProp, sizeof(DPLMSG_GETPROPERTY) );
msgGetProp.dwType = DPLSYS_GETPROPERTY;
msgGetProp.dwRequestID = 1; // guidPlayer is not used
msgGetProp.guidPropertyTag = DPLPROPERTY_MessagesSupported;
return g_pDPLobby->SendLobbyMessage( DPLMSG_STANDARD, 0, &msgGetProp,
sizeof(DPLMSG_GETPROPERTY) );
}
//-----------------------------------------------------------------------------
// Name: LobbyMessageReceive()
// Desc: Check for any lobby messages and handle them
// There are two modes:
// LMR_CONNECTIONSETTINGS - Waiting only for settings from a lobby
// LMR_PROPERTIES - Handle property message responses
//-----------------------------------------------------------------------------
HRESULT LobbyMessageReceive( DWORD dwMode )
{
HRESULT hr = NOERROR;
LPVOID lpMsgBuffer = NULL;
DWORD dwBufferSize = 0;
DWORD dwRequiredSize;
DWORD dwMsgFlags;
if( NULL == g_pDPLobby ) // No lobby interface
return DPERR_NOINTERFACE;
while( SUCCEEDED(hr) ) // Get all queued messages
{
dwRequiredSize = dwBufferSize;
hr = g_pDPLobby->ReceiveLobbyMessage( 0, 0, &dwMsgFlags,
lpMsgBuffer, &dwRequiredSize );
if( hr == DPERR_BUFFERTOOSMALL ) // Alloc msg buffer and try again
{
if( NULL == lpMsgBuffer )
lpMsgBuffer = GlobalAllocPtr( GHND, dwRequiredSize );
else
lpMsgBuffer = GlobalReAllocPtr( lpMsgBuffer, dwRequiredSize, 0 );
if( NULL == lpMsgBuffer)
return DPERR_NOMEMORY;
dwBufferSize = dwRequiredSize;
hr = S_OK;
}
else if( SUCCEEDED(hr) && dwRequiredSize >= sizeof(DPLMSG_GENERIC) )
{
// Decode the message
// Are we just looking for the CONNECTIONSETTINGS msg?
if( dwMode == LMR_CONNECTIONSETTINGS )
{
if( (dwMsgFlags & DPLMSG_SYSTEM) &&
((DPLMSG_GENERIC*)lpMsgBuffer)->dwType ==
DPLSYS_NEWCONNECTIONSETTINGS )
break;
else
TRACE(_T("Non CONNECTIONSETTINGS lobby message ignored\n"));
}
// Otherwise we handle only GetProperty responses
else if( (dwMsgFlags & DPLMSG_STANDARD) &&
((DPLMSG_GENERIC*)lpMsgBuffer)->dwType ==
DPLSYS_GETPROPERTYRESPONSE )
{
DPLMSG_GETPROPERTYRESPONSE* lpMsgGPR =
(DPLMSG_GETPROPERTYRESPONSE*)lpMsgBuffer;
if( IsEqualGUID( lpMsgGPR->guidPropertyTag,
DPLPROPERTY_MessagesSupported ) )
{
if( (BOOL)lpMsgGPR->dwPropertyData[0] ) // Supported
{
// So request our player instance guid
DPLMSG_GETPROPERTY msgGetProp;
ZeroMemory(&msgGetProp, sizeof(DPLMSG_GETPROPERTY));
msgGetProp.dwType = DPLSYS_GETPROPERTY;
msgGetProp.dwRequestID = 2;
// guidPlayer is left NULL
msgGetProp.guidPropertyTag = DPLPROPERTY_PlayerGuid;
hr = g_pDPLobby->SendLobbyMessage( DPLMSG_STANDARD, 0,
&msgGetProp,
sizeof(DPLMSG_GETPROPERTY) );
hr = S_OK; // keep fetching messages
}
else // not supported so close up shop
{
TRACE(_T("Lobby Messages not supported\n"));
DPLobbyRelease();
break;
}
}
else if( IsEqualGUID( lpMsgGPR->guidPropertyTag,
DPLPROPERTY_PlayerGuid ) )
{
// Have our player guid, ready to send property msgs
g_guidPlayer = ( (DPLDATA_PLAYERGUID*)
&lpMsgGPR->dwPropertyData)->guidPlayer;
g_bLobbyMsgSupported = TRUE;
}
}
else
TRACE(_T("Unrecognized lobby message ignored\n"));
}
}
if( lpMsgBuffer )
GlobalFreePtr( lpMsgBuffer );
return hr;
}
//-----------------------------------------------------------------------------
// Name: LobbyMessageSetProperty()
// Desc: Send a SetProperty message
//-----------------------------------------------------------------------------
HRESULT LobbyMessageSetProperty( const GUID* pPropTagGUID, VOID* pData,
DWORD dwDataSize )
{
HRESULT hr;
LPBYTE lpBuffer;
LPDPLMSG_SETPROPERTY lpMsgSP;
DWORD dwMsgSize;
if( NULL == g_pDPLobby )
return DPERR_NOCONNECTION;
if( NULL == g_bLobbyMsgSupported )
return DPERR_UNAVAILABLE;
// Allocate and pack up the message
// Property data starts at dwPropertyData[0] for the size calculation
dwMsgSize = sizeof(DPLMSG_SETPROPERTY) - sizeof(DWORD) + dwDataSize;
lpBuffer = (LPBYTE)GlobalAllocPtr(GHND, dwMsgSize);
if( NULL == lpBuffer )
return (DPERR_NOMEMORY);
lpMsgSP = (LPDPLMSG_SETPROPERTY)lpBuffer;
lpMsgSP->dwType = DPLSYS_SETPROPERTY;
lpMsgSP->dwRequestID = DPL_NOCONFIRMATION;
lpMsgSP->guidPlayer = g_guidPlayer; // player property assumed
lpMsgSP->guidPropertyTag = (*pPropTagGUID);
lpMsgSP->dwDataSize = dwDataSize;
memcpy( lpMsgSP->dwPropertyData, pData, dwDataSize );
hr = g_pDPLobby->SendLobbyMessage( DPLMSG_STANDARD, 0, lpBuffer, dwMsgSize );
GlobalFreePtr( lpBuffer );
return hr;
}

View File

@@ -0,0 +1,33 @@
//-----------------------------------------------------------------------------
// File: Lobby.h
//
// Desc: DP lobby related routines include file
//
// Copyright (C) 1995-2001 Microsoft Corporation. All Rights Reserved.
//-----------------------------------------------------------------------------
#define IDIRECTPLAY2_OR_GREATER
#include <dplobby.h>
//-----------------------------------------------------------------------------
// LobbyMessageReceive Modes
//-----------------------------------------------------------------------------
#define LMR_PROPERTIES 0
#define LMR_CONNECTIONSETTINGS 1
//-----------------------------------------------------------------------------
// Prototypes
//-----------------------------------------------------------------------------
HRESULT DPLobbyRelease();
HRESULT DPLobbySetConnectionSettings();
BOOL DoingLobbyMessages();
HRESULT LobbyMessageInit();
HRESULT LobbyMessageReceive( DWORD dwMode );
HRESULT LobbyMessageSetProperty( const GUID* pPropTagGUID, VOID* pData,
DWORD dwDataSize );

Binary file not shown.

After

Width:  |  Height:  |  Size: 518 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 518 B

Some files were not shown because too many files have changed in this diff Show More