Cleanung up arch/ a little bit; Added mouse delta time interval for more more accurate reading at high FPS

This commit is contained in:
zicodxx 2008-01-29 14:49:54 +00:00
parent 9e47ebc29f
commit b6f477a398
44 changed files with 40 additions and 9498 deletions

View file

@ -1,12 +1,16 @@
D2X-Rebirth Changelog
20080129
--------
SConstruct, arch/include/mouse.h, arch/ogl/gr.c, arch/ogl/ogl.c, arch/ogl/sdlgl.c, arch/sdl/mouse.c, include/internal.h, main/kconfig.c: Cleanung up arch/ a little bit; Added mouse delta time interval for more more accurate reading at high FPS
20080125
--------
arch/sdl/digi_mixer_music.c: allow custom MIDI in add-on hogs to be used without caching everything
20080114
20080124
--------
INSTALL.txt, main/gamerend.c, main/network.c, main/udp.c: Updated Docs - Data files mus bt lowercase; Fixed small Multiplayer issues
INSTALL.txt, main/gamerend.c, main/network.c, main/udp.c: Updated Docs - Data files must be lowercase; Fixed small Multiplayer issues
20080123
--------

View file

@ -394,13 +394,11 @@ if (sdl_only == 1):
print "building with SDL"
target = 'd2x-rebirth-sdl'
env.Append(CPPDEFINES = ['SDL_VIDEO'])
env.Append(CPPPATH = ['arch/sdl/include'])
common_sources += arch_sdl_sources
else:
print "building with OpenGL"
target = 'd2x-rebirth-gl'
env.Append(CPPDEFINES = ogldefines)
env.Append(CPPPATH = ['arch/ogl/include'])
common_sources += arch_ogl_sources
libs += ogllibs

View file

@ -1,19 +1,6 @@
/*
THE COMPUTER CODE CONTAINED HEREIN IS THE SOLE PROPERTY OF PARALLAX
SOFTWARE CORPORATION ("PARALLAX"). PARALLAX, IN DISTRIBUTING THE CODE TO
END-USERS, AND SUBJECT TO ALL OF THE TERMS AND CONDITIONS HEREIN, GRANTS A
ROYALTY-FREE, PERPETUAL LICENSE TO SUCH END-USERS FOR USE BY SUCH END-USERS
IN USING, DISPLAYING, AND CREATING DERIVATIVE WORKS THEREOF, SO LONG AS
SUCH USE, DISPLAY OR CREATION IS FOR NON-COMMERCIAL, ROYALTY OR REVENUE
FREE PURPOSES. IN NO EVENT SHALL THE END-USER USE THE COMPUTER CODE
CONTAINED HEREIN FOR REVENUE-BEARING PURPOSES. THE END-USER UNDERSTANDS
AND AGREES TO THE TERMS HEREIN AND ACCEPTS THE SAME BY USE OF THIS FILE.
COPYRIGHT 1993-1999 PARALLAX SOFTWARE CORPORATION. ALL RIGHTS RESERVED.
*/
/*
*
* Header for mouse functions
* SDL mouse driver header
*
*/
@ -23,14 +10,12 @@ COPYRIGHT 1993-1999 PARALLAX SOFTWARE CORPORATION. ALL RIGHTS RESERVED.
#include "pstypes.h"
#include "fix.h"
#ifdef MBTN_RIGHT
#undef MBTN_RIGHT
#endif
#define MBTN_LEFT 0
#define MOUSE_MAX_BUTTONS 8
#define Z_SENSITIVITY 100
#define MBTN_LEFT 0
#define MBTN_RIGHT 1
#define MBTN_MIDDLE 2
#define MBTN_Z_UP 3
#define MBTN_Z_UP 3
#define MBTN_Z_DOWN 4
#define MBTN_PITCH_BACKWARD 5
#define MBTN_PITCH_FORWARD 6
@ -38,47 +23,18 @@ COPYRIGHT 1993-1999 PARALLAX SOFTWARE CORPORATION. ALL RIGHTS RESERVED.
#define MBTN_BANK_RIGHT 8
#define MBTN_HEAD_LEFT 9
#define MBTN_HEAD_RIGHT 10
#define MOUSE_LBTN 1
#define MOUSE_RBTN 2
#define MOUSE_MBTN 4
#define MOUSE_LBTN 1
#define MOUSE_RBTN 2
#define MOUSE_MBTN 4
//========================================================================
// Check for mouse driver, reset driver if installed. returns number of
// buttons if driver is present.
#ifdef SVGALIB_INPUT
extern int d_mouse_init(int enable_cyberman); /* conflict with <vgamouse.h> */
#else
extern int mouse_init(int enable_cyberman);
#endif
/* changed from int to void */
extern void mouse_set_limits( int x1, int y1, int x2, int y2 );
extern void mouse_flush(); // clears all mice events...
//========================================================================
// Shutdowns mouse system.
#ifdef SVGALIB_INPUT
extern void d_mouse_close(); /* conflict with <vgamouse.h> */
#else
extern void mouse_close();
#endif
//========================================================================
extern void mouse_get_pos( int *x, int *y, int *z );
extern void mouse_get_delta( int *dx, int *dy, int *dz );
extern int mouse_get_btns();
extern void mouse_set_pos( int x, int y);
extern void mouse_get_cyberman_pos( int *x, int *y );
// Returns how long this button has been down since last call.
extern fix mouse_button_down_time(int button);
// Returns how many times this button has went down since last call.
extern int mouse_button_down_count(int button);
// Returns 1 if this button is currently down
extern int mouse_button_state(int button);
#endif

View file

@ -1,267 +0,0 @@
#ifndef _LINUX_JOYSTICK_H
#define _LINUX_JOYSTICK_H
/*
* /usr/include/linux/joystick.h Version 1.2
*
* Copyright (C) 1996-1998 Vojtech Pavlik
*/
#include <asm/types.h>
#include <asm/atomic.h>
#include <linux/module.h>
/*
* Version
*/
#define JS_VERSION 0x01020a
/*
* Types and constants for reading from /dev/js
*/
#define JS_EVENT_BUTTON 0x01 /* button pressed/released */
#define JS_EVENT_AXIS 0x02 /* joystick moved */
#define JS_EVENT_INIT 0x80 /* initial state of device */
struct js_event {
__u32 time; /* event timestamp in miliseconds */
__s16 value; /* value */
__u8 type; /* event type */
__u8 number; /* axis/button number */
};
/*
* IOCTL commands for joystick driver
*/
#define JSIOCGVERSION _IOR('j', 0x01, __u32) /* get driver version */
#define JSIOCGAXES _IOR('j', 0x11, __u8) /* get number of axes */
#define JSIOCGBUTTONS _IOR('j', 0x12, __u8) /* get number of buttons */
#define JSIOCGNAME(len) _IOC(_IOC_READ, 'j', 0x13, len) /* get identifier string */
#define JSIOCSCORR _IOW('j', 0x21, struct js_corr) /* set correction values */
#define JSIOCGCORR _IOR('j', 0x22, struct js_corr) /* get correction values */
/*
* Types and constants for get/set correction
*/
#define JS_CORR_NONE 0x00 /* returns raw values */
#define JS_CORR_BROKEN 0x01 /* broken line */
struct js_corr {
__s32 coef[8];
__s16 prec;
__u16 type;
};
/*
* v0.x compatibility definitions
*/
#define JS_RETURN sizeof(struct JS_DATA_TYPE)
#define JS_TRUE 1
#define JS_FALSE 0
#define JS_X_0 0x01
#define JS_Y_0 0x02
#define JS_X_1 0x04
#define JS_Y_1 0x08
#define JS_MAX 2
#define JS_DEF_TIMEOUT 0x1300
#define JS_DEF_CORR 0
#define JS_DEF_TIMELIMIT 10L
#define JS_SET_CAL 1
#define JS_GET_CAL 2
#define JS_SET_TIMEOUT 3
#define JS_GET_TIMEOUT 4
#define JS_SET_TIMELIMIT 5
#define JS_GET_TIMELIMIT 6
#define JS_GET_ALL 7
#define JS_SET_ALL 8
struct JS_DATA_TYPE {
int buttons;
int x;
int y;
};
struct JS_DATA_SAVE_TYPE {
int JS_TIMEOUT;
int BUSY;
long JS_EXPIRETIME;
long JS_TIMELIMIT;
struct JS_DATA_TYPE JS_SAVE;
struct JS_DATA_TYPE JS_CORR;
};
/*
* Internal definitions
*/
#ifdef __KERNEL__
#define JS_BUFF_SIZE 64 /* output buffer size */
#include <linux/version.h>
#ifndef KERNEL_VERSION
#define KERNEL_VERSION(a,b,c) (((a) << 16) + ((b) << 8) + (c))
#endif
#ifndef LINUX_VERSION_CODE
#error "You need to use at least 2.0 Linux kernel."
#endif
#if LINUX_VERSION_CODE < KERNEL_VERSION(2,0,0)
#error "You need to use at least 2.0 Linux kernel."
#endif
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,1,0)
#define JS_HAS_RDTSC (current_cpu_data.x86_capability & 0x10)
#include <linux/init.h>
#else
#ifdef MODULE
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,0,35)
#define JS_HAS_RDTSC (x86_capability & 0x10)
#else
#define JS_HAS_RDTSC 0
#endif
#else
#define JS_HAS_RDTSC (x86_capability & 0x10)
#endif
#define __initdata
#define __init
#define MODULE_AUTHOR(x)
#define MODULE_PARM(x,y)
#define MODULE_SUPPORTED_DEVICE(x)
#define signal_pending(x) (((x)->signal) & ~((x)->blocked))
#endif
/*
* Parport stuff
*/
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,1,0)
#define USE_PARPORT
#endif
#ifdef USE_PARPORT
#include <linux/parport.h>
#define JS_PAR_STATUS(y) parport_read_status(y->port)
#define JS_PAR_DATA_IN(y) parport_read_data(y->port)
#define JS_PAR_DATA_OUT(x,y) parport_write_data(y->port, x)
#define JS_PAR_CTRL_OUT(x,y) parport_write_control(y->port, x)
#else
#define JS_PAR_STATUS(y) inb(y+1)
#define JS_PAR_DATA_IN(y) inb(y)
#define JS_PAR_DATA_OUT(x,y) outb(x,y)
#define JS_PAR_CTRL_OUT(x,y) outb(x,y+2)
#endif
#define JS_PAR_STATUS_INVERT (0x80)
/*
* Internal types
*/
struct js_dev;
typedef int (*js_read_func)(void *info, int **axes, int **buttons);
typedef unsigned int (*js_time_func)(void);
typedef int (*js_delta_func)(unsigned int x, unsigned int y);
typedef int (*js_ops_func)(struct js_dev *dev);
struct js_data {
int *axes;
int *buttons;
};
struct js_dev {
struct js_dev *next;
struct js_list *list;
struct js_port *port;
struct wait_queue *wait;
struct js_data cur;
struct js_data new;
struct js_corr *corr;
struct js_event buff[JS_BUFF_SIZE];
js_ops_func open;
js_ops_func close;
int ahead;
int bhead;
int tail;
int num_axes;
int num_buttons;
char *name;
};
struct js_list {
struct js_list *next;
struct js_dev *dev;
int tail;
int startup;
};
struct js_port {
struct js_port *next;
struct js_port *prev;
js_read_func read;
struct js_dev **devs;
int **axes;
int **buttons;
struct js_corr **corr;
void *info;
int ndevs;
};
/*
* Sub-module interface
*/
extern unsigned int js_time_speed;
extern js_time_func js_get_time;
extern js_delta_func js_delta;
extern unsigned int js_time_speed_a;
extern js_time_func js_get_time_a;
extern js_delta_func js_delta_a;
extern struct js_port *js_register_port(struct js_port *port, void *info,
int devs, int infos, js_read_func read);
extern struct js_port *js_unregister_port(struct js_port *port);
extern int js_register_device(struct js_port *port, int number, int axes,
int buttons, char *name, js_ops_func open, js_ops_func close);
extern void js_unregister_device(struct js_dev *dev);
/*
* Kernel interface
*/
extern int js_init(void);
extern int js_am_init(void);
extern int js_an_init(void);
extern int js_as_init(void);
extern int js_console_init(void);
extern int js_db9_init(void);
extern int js_gr_init(void);
extern int js_l4_init(void);
extern int js_lt_init(void);
extern int js_sw_init(void);
extern int js_tm_init(void);
extern void js_am_setup(char *str, int *ints);
extern void js_an_setup(char *str, int *ints);
extern void js_as_setup(char *str, int *ints);
extern void js_console_setup(char *str, int *ints);
extern void js_db9_setup(char *str, int *ints);
extern void js_l4_setup(char *str, int *ints);
#endif /* __KERNEL__ */
#endif /* _LINUX_JOYSTICK_H */

View file

@ -1,20 +0,0 @@
#include <conf.h>
#include <sys/time.h>
#include <stdio.h>
#include "maths.h"
static struct timeval tv_old;
fix timer_get_fixed_seconds(void)
{
fix x;
struct timeval tv_now;
gettimeofday(&tv_now, NULL);
x=i2f(tv_now.tv_sec - tv_old.tv_sec) + fixdiv(i2f((tv_now.tv_usec - tv_old.tv_usec)/1000), i2f(1000));
return x;
}
void timer_init(void)
{
gettimeofday(&tv_old, NULL);
}

View file

@ -1,9 +1,7 @@
/* $Id: gr.c,v 1.1.1.1 2006/03/17 19:53:31 zicodxx Exp $ */
/*
*
* OGL video functions. - Added 9/15/99 Matthew Mueller
*
*
*/
#ifdef HAVE_CONFIG_H

View file

@ -1,9 +1,7 @@
/* $Id: ogl.c,v 1.1.1.1 2006/03/17 19:53:36 zicodxx Exp $ */
/*
*
* Graphics support functions for OpenGL.
*
*
*/
#ifdef HAVE_CONFIG_H

View file

@ -1,9 +1,7 @@
/* $Id: sdlgl.c,v 1.1.1.1 2006/03/17 19:53:36 zicodxx Exp $ */
/*
*
* Graphics functions for SDL-GL.
*
*
*/
#ifdef HAVE_CONFIG_H
@ -11,10 +9,6 @@
#endif
#include <SDL/SDL.h>
#ifdef SDL_IMAGE
#include <SDL_image.h>
#endif
#include "internal.h"
#include "vers_id.h"
#include "error.h"
@ -23,7 +17,8 @@
static int curx=-1,cury=-1,curfull=0;
void ogl_do_fullscreen_internal(void){
void ogl_do_fullscreen_internal(void)
{
ogl_init_window(curx,cury);
}
@ -43,20 +38,13 @@ int ogl_init_window(int x, int y)
if (gl_initialized){
if (x==curx && y==cury && curfull==ogl_fullscreen)
return 0;
#ifdef __linux__ // Windows, at least, seems to need to reload every time.
#ifdef __LINUX__ // Windows, at least, seems to need to reload every time.
if (ogl_fullscreen || curfull)
#endif
ogl_smash_texture_list_internal();//if we are or were fullscreen, changing vid mode will invalidate current textures
}
SDL_WM_SetCaption(DESCENT_VERSION, "Descent II");
#ifdef SDL_IMAGE
{
#include "descent.xpm"
SDL_WM_SetIcon(IMG_ReadXPMFromArray(pixmap), NULL);
}
#endif
if (!SDL_SetVideoMode(x, y, GameArg.DbgGlBpp, SDL_OPENGL | (ogl_fullscreen ? SDL_FULLSCREEN : 0)))
{
Error("Could not set %dx%dx%d opengl video mode: %s\n", x, y, GameArg.DbgGlBpp, SDL_GetError());
@ -69,17 +57,18 @@ int ogl_init_window(int x, int y)
return 0;
}
void ogl_destroy_window(void){
if (gl_initialized){
void ogl_destroy_window(void)
{
if (gl_initialized)
{
ogl_smash_texture_list_internal();
SDL_ShowCursor(1);
//gl_initialized=0;
//well..SDL doesn't really let you kill the window.. so we just need to wait for sdl_quit
}
return;
}
void ogl_init(void){
void ogl_init(void)
{
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE,0);
SDL_GL_SetAttribute(SDL_GL_ACCUM_RED_SIZE,0);
@ -89,6 +78,7 @@ void ogl_init(void){
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER,1);
}
void ogl_close(void){
void ogl_close(void)
{
ogl_destroy_window();
}

View file

@ -1,7 +1,6 @@
/* $Id: mouse.c,v 1.1.1.1 2006/03/17 19:53:41 zicodxx Exp $ */
/*
*
* SDL mouse driver.
* SDL mouse driver
*
*/
@ -10,7 +9,6 @@
#endif
#include <string.h>
#include <SDL/SDL.h>
#include "fix.h"
@ -18,13 +16,7 @@
#include "event.h"
#include "mouse.h"
#ifdef _WIN32_WCE
# define LANDSCAPE
#endif
#define MOUSE_MAX_BUTTONS 8
#define Z_SENSITIVITY 100
extern fix FrameTime;
struct mousebutton {
ubyte pressed;
@ -37,6 +29,7 @@ struct mousebutton {
static struct mouseinfo {
struct mousebutton buttons[MOUSE_MAX_BUTTONS];
int delta_x, delta_y, delta_z;
int delta_time;
int x,y,z;
} Mouse;
@ -86,17 +79,10 @@ void mouse_button_handler(SDL_MouseButtonEvent *mbe)
void mouse_motion_handler(SDL_MouseMotionEvent *mme)
{
#ifdef LANDSCAPE
Mouse.delta_y += mme->xrel;
Mouse.delta_x += mme->yrel;
Mouse.y += mme->xrel;
Mouse.x += mme->yrel;
#else
Mouse.delta_x += mme->xrel;
Mouse.delta_y += mme->yrel;
Mouse.x += mme->xrel;
Mouse.y += mme->yrel;
#endif
}
void mouse_flush() // clears all mice events...
@ -134,13 +120,19 @@ void mouse_get_pos( int *x, int *y, int *z )
void mouse_get_delta( int *dx, int *dy, int *dz )
{
Mouse.delta_time += FrameTime;
event_poll();
*dx = Mouse.delta_x;
*dy = Mouse.delta_y;
*dz = Mouse.delta_z;
Mouse.delta_x = 0;
Mouse.delta_y = 0;
Mouse.delta_z = 0;
// reset all ~33ms
if (Mouse.delta_time >= F1_0/30)
{
Mouse.delta_x = 0;
Mouse.delta_y = 0;
Mouse.delta_z = 0;
Mouse.delta_time = 0;
}
}
int mouse_get_btns()

Binary file not shown.

Before

Width:  |  Height:  |  Size: 66 KiB

View file

@ -1,220 +0,0 @@
//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
/////////////////////////////////////////////////////////////////////////////
//
// Accelerator
//
IDR_MAIN_ACCEL ACCELERATORS DISCARDABLE
BEGIN
VK_F1, IDM_HELP, VIRTKEY, SHIFT, NOINVERT
VK_F2, IDM_CHANGEDEVICE, VIRTKEY, SHIFT, NOINVERT
VK_F4, IDM_EXIT, VIRTKEY, ALT, NOINVERT
VK_RETURN, IDM_TOGGLESTART, VIRTKEY, NOINVERT
VK_RETURN, IDM_TOGGLEFULLSCREEN, VIRTKEY, ALT, NOINVERT
VK_SPACE, IDM_SINGLESTEP, VIRTKEY, SHIFT, NOINVERT
END
/////////////////////////////////////////////////////////////////////////////
//
// DESIGNINFO
//
#ifdef APSTUDIO_INVOKED
GUIDELINES DESIGNINFO DISCARDABLE
BEGIN
IDD_ABOUT, DIALOG
BEGIN
LEFTMARGIN, 7
RIGHTMARGIN, 236
VERTGUIDE, 28
VERTGUIDE, 215
TOPMARGIN, 7
BOTTOMMARGIN, 99
HORZGUIDE, 27
END
END
#endif // APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// Dialog
//
IDD_ABOUT DIALOG DISCARDABLE 0, 0, 243, 106
STYLE DS_MODALFRAME | DS_3DLOOK | DS_CENTER | WS_POPUP | WS_VISIBLE |
WS_CAPTION | WS_SYSMENU
CAPTION "About Direct3D Descent"
FONT 8, "MS Sans Serif"
BEGIN
DEFPUSHBUTTON "OK",IDOK,201,85,35,14
CTEXT "Based on original code by Parallax Software",IDC_STATIC,
7,46,229,14
CTEXT "Only for use with full version of Descent from Interplay Productions",
IDC_STATIC,7,65,229,14
ICON IDI_MAIN_ICON,IDC_STATIC,7,7,21,20
CTEXT "DOS/VGA to Win32/Direct3D conversion by Piers Haken",
IDC_STATIC,28,27,187,14
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_HELP
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_HELP
MENUITEM "&Change device...", IDM_CHANGEDEVICE
MENUITEM SEPARATOR
MENUITEM "E&xit", IDM_EXIT
END
END
/////////////////////////////////////////////////////////////////////////////
//
// Icon
//
// Icon with lowest ID value placed first to ensure application icon
// remains consistent on all systems.
IDI_MAIN_ICON ICON DISCARDABLE "d1x.ico"
#endif // English (U.S.) resources
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// English (U.K.) resources
#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENG)
#ifdef _WIN32
LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_UK
#pragma code_page(1252)
#endif //_WIN32
#ifndef _MAC
/////////////////////////////////////////////////////////////////////////////
//
// Version
//
VS_VERSION_INFO VERSIONINFO
FILEVERSION 0,0,0,1
PRODUCTVERSION 0,0,0,1
FILEFLAGSMASK 0x3fL
#ifdef _DEBUG
FILEFLAGS 0x1L
#else
FILEFLAGS 0x0L
#endif
FILEOS 0x40004L
FILETYPE 0x1L
FILESUBTYPE 0x0L
BEGIN
BLOCK "StringFileInfo"
BEGIN
BLOCK "080904b0"
BEGIN
VALUE "Comments", "Doesn't work very well\0"
VALUE "CompanyName", "Spong Technologies\0"
VALUE "FileDescription", "d1xd3d\0"
VALUE "FileVersion", "0, 0, 0, 1\0"
VALUE "InternalName", "d1xd3d\0"
VALUE "OriginalFilename", "d1xd3d.exe\0"
VALUE "ProductName", "Direct3D Descent\0"
VALUE "ProductVersion", "0, 0, 0, 1\0"
END
END
BLOCK "VarFileInfo"
BEGIN
VALUE "Translation", 0x809, 1200
END
END
#endif // !_MAC
#endif // English (U.K.) resources
/////////////////////////////////////////////////////////////////////////////
#ifndef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 3 resource.
//
/////////////////////////////////////////////////////////////////////////////
#endif // not APSTUDIO_INVOKED

Binary file not shown.

Before

Width:  |  Height:  |  Size: 953 B

View file

@ -1,641 +0,0 @@
//-----------------------------------------------------------------------------
// File: D3DEnum.cpp
//
// Desc: Class enumerate through the DirectDraw drivers, Direct3D devices,
// and the display modes available to each device.
//
//
// Copyright (c) 1997-1998 Microsoft Corporation. All rights reserved
//-----------------------------------------------------------------------------
#include <stdio.h>
// HACK!!!!!
#include <windows.h>
#ifndef SM_CMONITORS
#define SM_CMONITORS
DECLARE_HANDLE(HMONITOR);
#endif
#include "D3DEnum.h"
#include "D3DUtil.h"
//-----------------------------------------------------------------------------
// Constants and function prototypes for the user select driver dialog
//-----------------------------------------------------------------------------
DLGTEMPLATE* _BuildDriverSelectTemplate();
BOOL CALLBACK _DriverSelectProc( HWND, UINT, WPARAM, LPARAM );
//-----------------------------------------------------------------------------
// Global data for the enumerator functions
//-----------------------------------------------------------------------------
static LPDIRECTDRAW4 g_pDD = NULL; // Used for callbacks
static BOOL g_bRefRastEnumerated = FALSE; // For the reference rast
static BOOL g_bDevicesEnumerated = FALSE; // Used during enumeration
D3DEnum_DriverInfo* g_pFirstDriver = NULL; // List of DD drivers
D3DEnum_DriverInfo* g_pDefaultDriver = NULL; // Default driver
D3DEnum_DriverInfo* g_pCurrentDriver = NULL; // The selected DD driver
static HRESULT (*g_fnAppConfirmFn)(DDCAPS*, D3DDEVICEDESC*) = NULL;
//-----------------------------------------------------------------------------
// Local callback functions used during enumeration
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Name: EnumDisplayModesCallback()
// Desc: Callback function called for each display mode. Each available
// display mode is added to a list for further choosing from the app.
//-----------------------------------------------------------------------------
static HRESULT WINAPI EnumDisplayModesCallback( DDSURFACEDESC2* pddsd,
VOID* pvContext )
{
// Check parameters
if( NULL==pddsd || NULL==pvContext )
return DDENUMRET_CANCEL;
D3DEnum_DeviceInfo* pDevice = (D3DEnum_DeviceInfo*)pvContext;
D3DEnum_ModeInfo* pNewMode;
DWORD dwBitDepth = pDevice->ddDesc.dwDeviceRenderBitDepth;
DWORD dwModeDepth = pddsd->ddpfPixelFormat.dwRGBBitCount;
// Check mode for compatability with device. Skip 8-bit modes.
if( (32==dwModeDepth) && (0==(dwBitDepth&DDBD_32)) ) return DDENUMRET_OK;
if( (24==dwModeDepth) && (0==(dwBitDepth&DDBD_24)) ) return DDENUMRET_OK;
if( (16==dwModeDepth) && (0==(dwBitDepth&DDBD_16)) ) return DDENUMRET_OK;
if( ( 8==dwModeDepth) ) return DDENUMRET_OK;
// Create a new mode structure
if( NULL == ( pNewMode = new D3DEnum_ModeInfo ) )
return DDENUMRET_CANCEL;
// Initialize the new mode structure
ZeroMemory( pNewMode, sizeof(D3DEnum_ModeInfo) );
memcpy( &pNewMode->ddsd, pddsd, sizeof(DDSURFACEDESC2) );
sprintf( pNewMode->strDesc, TEXT("%ld x %ld x %ld"), pddsd->dwWidth,
pddsd->dwHeight, dwModeDepth );
// Link the new mode struct in the list of other display modes
D3DEnum_ModeInfo** pMode = &pDevice->pFirstMode;
while( *pMode )
pMode = &((*pMode)->pNext);
(*pMode) = pNewMode;
// If this is a 640x480x16 mode, save it as the default mode
if( ( 640 == pddsd->dwWidth ) && ( 480 == pddsd->dwHeight ) &&
( 16 == pddsd->ddpfPixelFormat.dwRGBBitCount ) )
pDevice->pCurrentMode = pNewMode;
if( NULL == pDevice->pCurrentMode )
pDevice->pCurrentMode = pNewMode;
return DDENUMRET_OK;
}
//-----------------------------------------------------------------------------
// Name: Enum3DDevicesCallback()
// Desc: Callback function called for each DirectX 3D device. The driver's
// attributes are added to the list of available drivers.
//-----------------------------------------------------------------------------
static HRESULT WINAPI Enum3DDevicesCallback( GUID* pGUID, LPSTR strDesc,
LPSTR strName, LPD3DDEVICEDESC pHALDesc,
LPD3DDEVICEDESC pHELDesc, LPVOID pvContext )
{
D3DEnum_DriverInfo* pDriver = (D3DEnum_DriverInfo*)pvContext;
D3DEnum_DeviceInfo* pNewDevice;
// Check params
if( NULL==pGUID || NULL==pHALDesc || NULL==pHELDesc || NULL==pDriver )
return D3DENUMRET_CANCEL;
// Handle specific device GUIDs. NullDevice renders nothing
if( IsEqualGUID( *pGUID, IID_IDirect3DNullDevice ) )
return D3DENUMRET_OK;
// Set a flag so we know enumeration is working. This is just a feature to
// help return more informative return codes later on.
g_bDevicesEnumerated = TRUE;
// Get info about this device.
BOOL bIsHardware = ( 0 != pHALDesc->dwFlags );
D3DDEVICEDESC* pDesc = bIsHardware ? pHALDesc : pHELDesc;
// Only enumerate software rasterizers for the primary device (which has
// a NULL GUID). This is to avoid duplicates
if( pDriver->pGUID != NULL )
if( FALSE == bIsHardware )
return D3DENUMRET_OK;
// Give the app a chance to accept or reject this device, based on
// what feature set it supports
if( g_fnAppConfirmFn )
if( FAILED( g_fnAppConfirmFn( &pDriver->ddDriverCaps, pDesc ) ) )
return D3DENUMRET_OK;
// Create a new D3D Driver struct
if( NULL == ( pNewDevice = new D3DEnum_DeviceInfo ) )
return D3DENUMRET_CANCEL;
ZeroMemory( pNewDevice, sizeof(D3DEnum_DeviceInfo) );
// Copy remaining device attributes
memcpy( &pNewDevice->guid, pGUID, sizeof(GUID) );
pNewDevice->pGUID = &pNewDevice->guid;
strncpy( pNewDevice->strName, strName, 39 );
memcpy( &pNewDevice->ddDesc, pDesc, sizeof(D3DDEVICEDESC) );
pNewDevice->bIsHardware = bIsHardware;
if( pNewDevice->bIsHardware )
pDriver->pCurrentDevice = pNewDevice;
else
{
if( NULL == pDriver->pCurrentDevice )
if( D3DCOLOR_RGB & pHELDesc->dcmColorModel )
pDriver->pCurrentDevice = pNewDevice;
}
// Enumerate the display modes
g_pDD->EnumDisplayModes( 0, NULL, pNewDevice, EnumDisplayModesCallback );
// Get the display mode's depth
DDSURFACEDESC2 ddsd;
ddsd.dwSize = sizeof(DDSURFACEDESC2);
g_pDD->GetDisplayMode( &ddsd );
DWORD dwDisplayBPP = ddsd.ddpfPixelFormat.dwRGBBitCount;
// Set the initial bWindowed flag if the device can render in a window and
// supports the current display mode
if( pDriver->ddDriverCaps.dwCaps2 & DDCAPS2_CANRENDERWINDOWED )
{
for( D3DEnum_ModeInfo* pMode=pNewDevice->pFirstMode; pMode;
pMode = pMode->pNext )
{
if( pMode->ddsd.ddpfPixelFormat.dwRGBBitCount == dwDisplayBPP )
{
pNewDevice->bCompatbileWithDesktop = TRUE;
if( NULL == pDriver->pGUID )
pNewDevice->bWindowed = TRUE;
}
}
}
if( pNewDevice->pFirstMode )
{
// Link it with the other D3D drivers in the DD Driver struct
D3DEnum_DeviceInfo** pDevice = &pDriver->pFirstDevice;
while( *pDevice )
pDevice = &((*pDevice)->pNext);
(*pDevice) = pNewDevice;
}
else
// Device has no modes, so delete it
delete pNewDevice;
if( IsEqualGUID( *pGUID, IID_IDirect3DRefDevice ) )
g_bRefRastEnumerated = TRUE;
return D3DENUMRET_OK;
}
//-----------------------------------------------------------------------------
// Name: DirectDrawEnumCallbackEx()
// Desc: Callback function called for each DirectDraw driver. Unless we have
// multimon or a type of card which uses a separate 2D card in
// conjunction with the 3D card, this is only done once.
//-----------------------------------------------------------------------------
static BOOL WINAPI DirectDrawEnumCallbackEx( GUID FAR* pGUID, LPSTR strDesc,
LPSTR strName, VOID*,
HMONITOR hMonitor )
{
// Use the GUID to create the DirectDraw object, so that information
// can be extracted from it.
LPDIRECTDRAW pDD;
if( FAILED( DirectDrawCreate( pGUID, &pDD, 0L ) ) )
{
DEBUG_MSG( TEXT("Can't create DDraw during enumeration!") );
return D3DENUMRET_OK;
}
// Query the DirectDraw driver for access to Direct3D.
if( FAILED( pDD->QueryInterface( IID_IDirectDraw4, (VOID**)&g_pDD ) ) )
{
DEBUG_MSG( TEXT("Can't query IDirectDraw4 during enumeration!") );
pDD->Release();
return D3DENUMRET_OK;
}
pDD->Release();
// Query the DirectDraw driver for access to Direct3D.
LPDIRECT3D3 pD3D;
if( FAILED( g_pDD->QueryInterface( IID_IDirect3D3, (VOID**)&pD3D ) ) )
{
DEBUG_MSG( TEXT("Can't query IDirect3D3 during enumeration!") );
g_pDD->Release();
return D3DENUMRET_OK;
}
// Copy the DDDriver info into a new DriverInfo struct
D3DEnum_DriverInfo* pNewDriver = new D3DEnum_DriverInfo;
if( NULL == pNewDriver )
return D3DENUMRET_CANCEL;
ZeroMemory( pNewDriver, sizeof(D3DEnum_DriverInfo) );
// Copy the GUID (if specified) and the driver name
if( NULL != pGUID )
{
memcpy( &pNewDriver->guid, pGUID, sizeof(GUID) );
pNewDriver->pGUID = &pNewDriver->guid;
}
strncpy( pNewDriver->strDesc, strDesc, 39 );
strncpy( pNewDriver->strName, strName, 39 );
pNewDriver->hMonitor = hMonitor;
// Get the caps bits for the driver
pNewDriver->ddDriverCaps.dwSize = sizeof(DDCAPS);
pNewDriver->ddHELCaps.dwSize = sizeof(DDCAPS);
g_pDD->GetCaps( &pNewDriver->ddDriverCaps, &pNewDriver->ddHELCaps );
// Now, enumerate all the 3D devices
pD3D->EnumDevices( Enum3DDevicesCallback, pNewDriver );
if( pNewDriver->pFirstDevice )
{
// Link the new DDDriver with the global list
D3DEnum_DriverInfo** pDriver = &g_pFirstDriver;
while( *pDriver )
pDriver = &((*pDriver)->pNext);
(*pDriver) = pNewDriver;
// Decide if this is a good default driver
if( NULL == pGUID )
g_pCurrentDriver = pNewDriver;
}
else
// Driver has no devices, so delete it
delete pNewDriver;
pD3D->Release();
g_pDD->Release();
return DDENUMRET_OK;
}
//-----------------------------------------------------------------------------
// Name: DirectDrawEnumCallback()
// Desc: Non-mulitmon version of the ddraw enumeration callback
//-----------------------------------------------------------------------------
static BOOL WINAPI DirectDrawEnumCallback( GUID FAR* pGUID, LPSTR strDesc,
LPSTR strName, VOID* )
{
return DirectDrawEnumCallbackEx( pGUID, strDesc, strName, NULL, NULL );
}
//-----------------------------------------------------------------------------
// Name: D3DEnum_FreeResources()
// Desc: Frees all resources used for driver enumeration
//-----------------------------------------------------------------------------
VOID D3DEnum_FreeResources()
{
// Loop through each driver, and delete everything
while( g_pFirstDriver )
{
D3DEnum_DriverInfo* pDriverVictim = g_pFirstDriver;
g_pFirstDriver = g_pFirstDriver->pNext;
while( pDriverVictim->pFirstDevice )
{
D3DEnum_DeviceInfo* pDeviceVictim = pDriverVictim->pFirstDevice;
pDriverVictim->pFirstDevice = pDeviceVictim->pNext;
while( pDeviceVictim->pFirstMode )
{
D3DEnum_ModeInfo* pModeVictim = pDeviceVictim->pFirstMode;
pDeviceVictim->pFirstMode = pModeVictim->pNext;
delete pModeVictim;
}
delete pDeviceVictim;
}
delete pDriverVictim;
}
}
//-----------------------------------------------------------------------------
// Name: RefreshListForDesktopCompatibility()
// Desc: Loops through list of devices, and marks a flag for whether the device
// is compatible with the desktop bit depth.
//-----------------------------------------------------------------------------
static VOID RefreshListForDesktopCompatibility()
{
// Get the currect display mode description
LPDIRECTDRAW pDD;
DDSURFACEDESC ddsd;
if( FAILED( DirectDrawCreate( NULL, &pDD, NULL ) ) )
return;
ddsd.dwSize = sizeof(DDSURFACEDESC);
pDD->GetDisplayMode( &ddsd );
pDD->Release();
// Get the display mode's depth
DWORD dwDisplayBPP = ddsd.ddpfPixelFormat.dwRGBBitCount;
// Loop through the devices, and check if any modes works with the current
// display setting
for( D3DEnum_DriverInfo* pDriver = g_pFirstDriver; pDriver;
pDriver = pDriver->pNext )
{
for( D3DEnum_DeviceInfo* pDevice=pDriver->pFirstDevice; pDevice;
pDevice = pDevice->pNext )
{
pDevice->bCompatbileWithDesktop = FALSE;
for( D3DEnum_ModeInfo* pMode=pDevice->pFirstMode; pMode;
pMode = pMode->pNext )
{
if( pMode->ddsd.ddpfPixelFormat.dwRGBBitCount == dwDisplayBPP )
pDevice->bCompatbileWithDesktop = TRUE;
}
}
}
}
//-----------------------------------------------------------------------------
// Name: D3DEnum_EnumerateDevices()
// Desc: Enumerates all drivers, devices, and modes. The optional app-supplied
// callback is called for each enumerated device, to confirm that the
// device supports the feature set required by the app.
//-----------------------------------------------------------------------------
HRESULT D3DEnum_EnumerateDevices(
HRESULT (*AppConfirmFn)(DDCAPS*, D3DDEVICEDESC*) )
{
g_fnAppConfirmFn = AppConfirmFn;
g_bRefRastEnumerated = FALSE;
// We need to manually get the procedure address for the DDrawEnumEx()
// function.
HMODULE hDDrawDLL = GetModuleHandle("DDRAW.DLL");
if( NULL == hDDrawDLL )
{
DEBUG_MSG( TEXT("Can't load DDRAW.DLL!") );
return D3DENUMERR_NODIRECTDRAW;
}
// Find the DDraw enumeration function, and call it
LPDIRECTDRAWENUMERATEEX pDDrawEnumFn = (LPDIRECTDRAWENUMERATEEX)
GetProcAddress( hDDrawDLL, "DirectDrawEnumerateExA" );
if( pDDrawEnumFn )
pDDrawEnumFn( DirectDrawEnumCallbackEx, NULL,
DDENUM_ATTACHEDSECONDARYDEVICES |
DDENUM_DETACHEDSECONDARYDEVICES |
DDENUM_NONDISPLAYDEVICES );
else
DirectDrawEnumerate( DirectDrawEnumCallback, NULL );
// Select a driver. Ask for a hardware device that renders in a window
return D3DEnum_SelectDefaultDriver( NULL );
}
//-----------------------------------------------------------------------------
// Name: D3DEnum_SelectDefaultDriver()
// Desc: Picks a default driver according to the passed in flags.
//-----------------------------------------------------------------------------
HRESULT D3DEnum_SelectDefaultDriver( DWORD dwFlags )
{
// Refresh the list of devices to mark which devices (if any) are
// compatible with the current desktop (ie. can render in a window).
RefreshListForDesktopCompatibility();
// If a specific driver was requested, perform that search here
if( dwFlags & 0x0000003c )
{
for( D3DEnum_DriverInfo* pDriver = g_pFirstDriver; pDriver;
pDriver = pDriver->pNext )
{
for( D3DEnum_DeviceInfo* pDevice = pDriver->pFirstDevice; pDevice;
pDevice = pDevice->pNext )
{
BOOL bFound = FALSE;
if( IsEqualGUID( *pDevice->pGUID, IID_IDirect3DRGBDevice ) )
{
if( dwFlags & D3DENUM_RGBEMULATION )
bFound = TRUE;
}
else if( IsEqualGUID( *pDevice->pGUID, IID_IDirect3DRefDevice ) )
{
if( dwFlags & D3DENUM_REFERENCERAST )
bFound = TRUE;
}
else
{
if( dwFlags & D3DENUM_PRIMARYHAL )
if( pDriver == g_pFirstDriver )
bFound = TRUE;
if( dwFlags & D3DENUM_SECONDARYHAL )
if( pDriver != g_pFirstDriver )
bFound = TRUE;
}
if( bFound )
{
g_pCurrentDriver = pDriver;
g_pCurrentDriver->pCurrentDevice = pDevice;
return S_OK;
}
}
}
return D3DENUMERR_NOTFOUND;
}
// Do 4 passes, looping through drivers, devices and modes. The 1st pass
// searches for hardware. The 2nd pass looks for software devices. The
// final two passes allow fullscreen modes.
for( WORD pass=0; pass<4; pass++ )
{
BOOL bSeekHardware = ( pass & 0x1 ) ? FALSE : TRUE;
BOOL bSeekWindowed = ( pass & 0x2 ) ? FALSE : TRUE;
// Skip the passes we aren't allowing
if( (TRUE==bSeekHardware) && (dwFlags&D3DENUM_SOFTWAREONLY) )
continue;
if( (TRUE==bSeekWindowed) && (dwFlags&D3DENUM_FULLSCREENONLY) )
continue;
for( D3DEnum_DriverInfo* pDriver = g_pFirstDriver; pDriver;
pDriver = pDriver->pNext )
{
DDCAPS* pCaps = &pDriver->ddDriverCaps;
if( bSeekWindowed )
if( 0 == ( pCaps->dwCaps2 & DDCAPS2_CANRENDERWINDOWED ) )
continue;
for( D3DEnum_DeviceInfo* pDevice = pDriver->pFirstDevice; pDevice;
pDevice = pDevice->pNext )
{
if( bSeekHardware != pDevice->bIsHardware )
continue;
if( bSeekWindowed && FALSE == pDevice->bCompatbileWithDesktop )
continue;
pDevice->bWindowed = bSeekWindowed;
g_pCurrentDriver = pDriver;
g_pCurrentDriver->pCurrentDevice = pDevice;
return S_OK;
}
}
}
// No compatible devices were found. Return an error code
if( FALSE == g_bDevicesEnumerated )
return D3DENUMERR_ENUMERATIONFAILED; // Enumeration really did fail
if( FALSE == g_bRefRastEnumerated )
return D3DENUMERR_SUGGESTREFRAST; // Suggest enabling the RefRast
return D3DENUMERR_NOCOMPATIBLEDEVICES;
}
//-----------------------------------------------------------------------------
// Name: D3DEnum_UserDlgSelectDriver()
// Desc: Displays a dialog box for the user to select a driver/device/mode.
// The return values are akin to the Windows DialogBox() function.
//-----------------------------------------------------------------------------
INT D3DEnum_UserDlgSelectDriver( HWND hwndParent, BOOL bCurrentlyWindowed )
{
INT nResult = -1;
// Check in case drivers weren't properly enumerated beforehand.
if( NULL == g_pCurrentDriver )
return -1;
// Refresh the list of devices to mark which devices (if any) are
// compatible with the current desktop (ie. can render in a window).
RefreshListForDesktopCompatibility();
// Match the current windowed-vs-fullscreen state
g_pCurrentDriver->pCurrentDevice->bWindowed = bCurrentlyWindowed;
// Pop up a dialog box for the user's choice of driver/device/mode
HINSTANCE hInstance = (HINSTANCE)GetWindowLong( hwndParent,
GWL_HINSTANCE );
// Create dynamic dialog template
DLGTEMPLATE* pDlgSelect = _BuildDriverSelectTemplate();
if( pDlgSelect )
{
// Create dialog box from template
nResult = DialogBoxIndirectParam( hInstance, pDlgSelect, hwndParent,
(DLGPROC)_DriverSelectProc, 0L );
delete pDlgSelect;
}
return nResult;
}
//-----------------------------------------------------------------------------
// Name: D3DEnum_GetSelectedDriver()
// Desc: Returns the currently selected driver, device, and display mode
//-----------------------------------------------------------------------------
HRESULT D3DEnum_GetSelectedDriver( LPGUID* ppDriverGUID, LPGUID* ppDeviceGUID,
LPDDSURFACEDESC2* ppddsd, BOOL* pbWindowed,
BOOL* pbIsHardware )
{
// Check parans
if( (!ppDriverGUID) || (!ppDeviceGUID) )
return E_INVALIDARG;
// Abort if things weren't setup correctly
if( NULL == g_pCurrentDriver )
return D3DENUMERR_ENUMERATIONFAILED;
// Copy the driver and device GUID ptrs
(*ppDriverGUID) = g_pCurrentDriver->pGUID;
(*ppDeviceGUID) = g_pCurrentDriver->pCurrentDevice->pGUID;
if( ppddsd )
(*ppddsd) = &g_pCurrentDriver->pCurrentDevice->pCurrentMode->ddsd;
if( pbWindowed )
(*pbWindowed) = g_pCurrentDriver->pCurrentDevice->bWindowed;
if( pbIsHardware )
(*pbIsHardware) = g_pCurrentDriver->pCurrentDevice->bIsHardware;
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: D3DEnum_GetSelectedDriver()
// Desc: Returns the currently selected driver, device, and display mode
//-----------------------------------------------------------------------------
HRESULT D3DEnum_GetSelectedDriver( D3DEnum_DriverInfo** ppDriverInfo,
D3DEnum_DeviceInfo** ppDeviceInfo )
{
// Abort if things weren't setup correctly
if( NULL == g_pCurrentDriver )
return D3DENUMERR_ENUMERATIONFAILED;
// Copy the driver and device info ptrs
if( ppDriverInfo ) *ppDriverInfo = g_pCurrentDriver;
if( ppDeviceInfo ) *ppDeviceInfo = g_pCurrentDriver->pCurrentDevice;
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: D3DEnum_GetFirstDriver()
// Desc: Returns a ptr to the first DriverInfo structure in the list.
//-----------------------------------------------------------------------------
D3DEnum_DriverInfo* D3DEnum_GetFirstDriver()
{
return g_pFirstDriver;
}

View file

@ -1,180 +0,0 @@
//-----------------------------------------------------------------------------
// File: D3DEnum.h
//
// Desc: Functions which enumerate through the DirectDraw drivers, Direct3D
// devices, and the display modes available to each device.
//
//
// Copyright (C) 1997 Microsoft Corporation. All rights reserved
//-----------------------------------------------------------------------------
#ifndef D3DENUM_H
#define D3DENUM_H
#include <ddraw.h>
#include <d3d.h>
//-----------------------------------------------------------------------------
// Name: D3DEnum_ModeInfo
// Desc: Linked-list structure to hold information about a display mode. This
// info is stored as a width, height, bpp, and pixelformat within a
// DDSURFACEDESC2.
//-----------------------------------------------------------------------------
struct D3DEnum_ModeInfo
{
DDSURFACEDESC2 ddsd;
CHAR strDesc[40];
D3DEnum_ModeInfo* pNext;
};
//-----------------------------------------------------------------------------
// Name: D3DEnum_DeviceInfo
// Desc: Linked-list structure to hold information about a Direct3D device. The
// primary information recorded here is the D3DDEVICEDESC and a ptr to a
// linked-list of valid display modes.
//-----------------------------------------------------------------------------
struct D3DEnum_DeviceInfo
{
GUID guid;
GUID* pGUID;
CHAR strName[40];
D3DDEVICEDESC ddDesc;
BOOL bIsHardware;
BOOL bCompatbileWithDesktop;
BOOL bWindowed;
D3DEnum_ModeInfo* pCurrentMode;
D3DEnum_ModeInfo* pFirstMode;
D3DEnum_DeviceInfo* pNext;
};
//-----------------------------------------------------------------------------
// Name: D3DEnum_DriverInfo
// Desc: Linked-list structure to hold information about a DirectX driver. The
// info stored is the capability bits for the driver plus a linked-list
// of valid Direct3D devices for the driver. Note: most systems will only
// have one driver. The exception are multi-monitor systems, and systems
// with non-GDI 3D video cards.
//-----------------------------------------------------------------------------
struct D3DEnum_DriverInfo
{
GUID guid;
GUID* pGUID;
CHAR strDesc[40];
CHAR strName[40];
DDCAPS ddDriverCaps;
DDCAPS ddHELCaps;
HANDLE hMonitor;
D3DEnum_DeviceInfo* pCurrentDevice;
D3DEnum_DeviceInfo* pFirstDevice;
D3DEnum_DriverInfo* pNext;
};
//-----------------------------------------------------------------------------
// Name: D3DEnum_EnumerateDevices()
// Desc: Enumerates all drivers, devices, and modes. The optional app-supplied
// callback is called for each enumerated device, to confirm that the
// device supports the feature set required by the app.
//-----------------------------------------------------------------------------
HRESULT D3DEnum_EnumerateDevices(
HRESULT (*AppConfirmFn)(DDCAPS*, D3DDEVICEDESC*) );
//-----------------------------------------------------------------------------
// Name: D3DEnum_FreeResources()
// Desc: Frees all resources used for driver enumeration
//-----------------------------------------------------------------------------
VOID D3DEnum_FreeResources();
//-----------------------------------------------------------------------------
// Name: D3DEnum_SelectDefaultDriver()
// Desc: Picks a driver based on a set of passed in criteria.
//-----------------------------------------------------------------------------
HRESULT D3DEnum_SelectDefaultDriver( DWORD dwFlags );
#define D3DENUM_SOFTWAREONLY 0x00000001
#define D3DENUM_FULLSCREENONLY 0x00000002
#define D3DENUM_RGBEMULATION 0x00000004
#define D3DENUM_REFERENCERAST 0x00000008
#define D3DENUM_PRIMARYHAL 0x00000010
#define D3DENUM_SECONDARYHAL 0x00000020
//-----------------------------------------------------------------------------
// Name: D3DEnum_UserDlgSelectDriver()
// Desc: Prompts the user with a dialog box, from which to choose a DD driver,
// D3D device, and compatible display mode. The function will return
// IDOK if a new driver/device/mode was selected, or IDCANCEL if not.
// Any error will result in a -1 for a return code.
//-----------------------------------------------------------------------------
INT D3DEnum_UserDlgSelectDriver( HWND hwndParent, BOOL bCurrentlyWindowed );
//-----------------------------------------------------------------------------
// Name: D3DEnum_GetSelectedDriver()
// Desc: Returns the currently selected driver, device, and display mode.
//-----------------------------------------------------------------------------
HRESULT D3DEnum_GetSelectedDriver( LPGUID* ppDriverGUID, LPGUID* ppDeviceGuid,
LPDDSURFACEDESC2* pddsdDisplayMode = NULL,
BOOL* pbWindowed = NULL,
BOOL* pbIsHardware = NULL );
//-----------------------------------------------------------------------------
// Name: D3DEnum_GetSelectedDriver()
// Desc: Returns the currently selected driver, device, and display mode.
//-----------------------------------------------------------------------------
HRESULT D3DEnum_GetSelectedDriver( D3DEnum_DriverInfo** ppDriverInfo,
D3DEnum_DeviceInfo** ppDeviceInfo );
//-----------------------------------------------------------------------------
// Name: D3DEnum_GetFirstDriver()
// Desc: Returns a ptr to the first DriverInfo structure in the tree holding
// the device/driver/mode enumeration information.
//-----------------------------------------------------------------------------
D3DEnum_DriverInfo* D3DEnum_GetFirstDriver();
//-----------------------------------------------------------------------------
// Error codes
//-----------------------------------------------------------------------------
#define D3DENUMERR_ENUMERATIONFAILED 0x81000001 // Enumeration failed
#define D3DENUMERR_SUGGESTREFRAST 0x81000002 // Suggest using the RefRast
#define D3DENUMERR_NOCOMPATIBLEDEVICES 0x81000003 // No devices were found that
// meet the app's desired
// capabilities
#define D3DENUMERR_NODIRECTDRAW 0x81000004 // DDraw couldn't initialize
#define D3DENUMERR_NOTFOUND 0x81000005 // Requested device not found
#endif // D3DENUM_H

View file

@ -1,754 +0,0 @@
//-----------------------------------------------------------------------------
// File: D3DFrame.cpp
//
// Desc: Class to manage the Direct3D environment objects such as buffers,
// viewports, and 3D devices.
//
// The class is initialized with the Initialize() function, after which
// the Get????() functions can be used to access the objects needed for
// rendering. If the device or display needs to be changed, the
// ChangeDevice() function can be called. If the display window is moved
// the changes need to be reported with the Move() function.
//
// After rendering a frame, the ShowFrame() function filps or blits the
// backbuffer contents to the primary. If surfaces are lost, they can be
// restored with the RestoreSurfaces() function. Finally, if normal
// Windows output is needed, the FlipToGDISurface() provides a GDI
// surface to draw on.
//
//
// Copyright (c) 1995-1998 by Microsoft, all rights reserved
//-----------------------------------------------------------------------------
#include <windows.h>
#include "D3DFrame.h"
#include "D3DUtil.h"
//-----------------------------------------------------------------------------
// Name: EnumZBufferFormatsCallback()
// Desc: Enumeration function to report valid pixel formats for z-buffers.
//-----------------------------------------------------------------------------
static HRESULT WINAPI EnumZBufferFormatsCallback( DDPIXELFORMAT* pddpf,
VOID* pddpfDesired )
{
if( NULL==pddpf || NULL==pddpfDesired )
return D3DENUMRET_CANCEL;
// If the current pixel format's match the desired ones (DDPF_ZBUFFER and
// possibly DDPF_STENCILBUFFER), lets copy it and return. This function is
// not choosy...it accepts the first valid format that comes along.
if( pddpf->dwFlags == ((DDPIXELFORMAT*)pddpfDesired)->dwFlags )
{
memcpy( pddpfDesired, pddpf, sizeof(DDPIXELFORMAT) );
// We're happy with a 16-bit z-buffer. Otherwise, keep looking.
if( pddpf->dwZBufferBitDepth == 16 )
return D3DENUMRET_CANCEL;
}
return D3DENUMRET_OK;
}
//-----------------------------------------------------------------------------
// Name: CD3DFramework()
// Desc: The constructor. Clears static variables
//-----------------------------------------------------------------------------
CD3DFramework::CD3DFramework()
{
m_hWnd = NULL;
m_bIsFullscreen = FALSE;
m_dwRenderWidth = 0L;
m_dwRenderHeight = 0L;
m_pddsFrontBuffer = NULL;
m_pddsBackBuffer = NULL;
m_pddsRenderTarget = NULL;
m_pddsZBuffer = NULL;
m_pd3dDevice = NULL;
m_pvViewport = NULL;
m_pDD = NULL;
m_pD3D = NULL;
m_dwDeviceMemType = NULL;
}
//-----------------------------------------------------------------------------
// Name: ~CD3DFramework()
// Desc: The destructor. Deletes all objects
//-----------------------------------------------------------------------------
CD3DFramework::~CD3DFramework()
{
DestroyObjects();
}
//-----------------------------------------------------------------------------
// Name: DestroyObjects()
// Desc: Cleans everything up upon deletion. This code returns an error
// if any of the objects have remaining reference counts.
//-----------------------------------------------------------------------------
HRESULT CD3DFramework::DestroyObjects()
{
LONG nDD = 0L; // Number of outstanding DDraw references
LONG nD3D = 0L; // Number of outstanding D3DDevice references
SAFE_RELEASE( m_pvViewport );
// Do a safe check for releasing the D3DDEVICE. RefCount must be zero.
if( m_pd3dDevice )
if( 0 < ( nD3D = m_pd3dDevice->Release() ) )
DEBUG_MSG( TEXT("Error: D3DDevice object is still referenced!") );
m_pd3dDevice = NULL;
// In windowed mode, release the explicity created backbuffer.
if( FALSE == m_bIsFullscreen )
SAFE_RELEASE( m_pddsBackBuffer );
SAFE_RELEASE( m_pddsRenderTarget ); //Note: release before frontbuffer
SAFE_RELEASE( m_pddsZBuffer );
SAFE_RELEASE( m_pddsFrontBuffer );
SAFE_RELEASE( m_pD3D );
// Do a safe check for releasing DDRAW. RefCount must be zero.
if( m_pDD )
{
m_pDD->SetCooperativeLevel( m_hWnd, DDSCL_NORMAL );
if( 0 < ( nDD = m_pDD->Release() ) )
DEBUG_MSG( TEXT("Error: DDraw object is still referenced!") );
}
m_pDD = NULL;
// Return successful, unless there are outstanding DD or D3DDevice refs.
return ( nDD==0 && nD3D==0 ) ? S_OK : D3DFWERR_NONZEROREFCOUNT;
}
//-----------------------------------------------------------------------------
// Name: Initialize()
// Desc: Creates the internal objects for the framework
//-----------------------------------------------------------------------------
HRESULT CD3DFramework::Initialize( HWND hWnd, GUID* pDriverGUID,
GUID* pDeviceGUID, DDSURFACEDESC2* pMode,
DWORD dwFlags )
{
HRESULT hr;
// Check params. A NULL mode is valid for windowed modes only. A NULL
// device GUID is legal for apps that only want 2D support.
if( NULL==hWnd || ( NULL==pMode && (dwFlags&D3DFW_FULLSCREEN) ) )
return E_INVALIDARG;
// Setup state for windowed/fullscreen mode
m_hWnd = hWnd;
m_bIsFullscreen = ( dwFlags & D3DFW_FULLSCREEN ) ? TRUE : FALSE;
// Create the D3D rendering environment (surfaces, device, viewport, etc.)
if( FAILED( hr = CreateEnvironment( pDriverGUID, pDeviceGUID, pMode,
dwFlags ) ) )
{
DestroyObjects();
if( E_FAIL == hr )
hr = D3DFWERR_INITIALIZATIONFAILED;
}
return hr;
}
//-----------------------------------------------------------------------------
// Name: CreateEnvironment()
// Desc: Creates the internal objects for the framework
//-----------------------------------------------------------------------------
HRESULT CD3DFramework::CreateEnvironment( GUID* pDriverGUID, GUID* pDeviceGUID,
DDSURFACEDESC2* pMode, DWORD dwFlags )
{
HRESULT hr;
// Create the DDraw object
if( FAILED( hr = CreateDirectDraw( pDriverGUID, dwFlags ) ) )
return hr;
// Create the Direct3D object
if( pDeviceGUID )
if( FAILED( hr = CreateDirect3D( pDeviceGUID, dwFlags ) ) )
return hr;
// Create the front and back buffers, and attach a clipper
if( FAILED( hr = CreateBuffers( pMode, dwFlags ) ) )
return hr;
// If there is no device GUID, then the app only wants 2D, so we're done
if( NULL == pDeviceGUID )
return S_OK;
// Create and attach the zbuffer
if( dwFlags & D3DFW_ZBUFFER )
if( FAILED( hr = CreateZBuffer() ) )
return hr;
// Query the render buffer for the 3ddevice
if( FAILED( hr = Create3DDevice( pDeviceGUID ) ) )
return hr;
// Create and set the viewport
if( FAILED( hr = CreateViewport() ) )
return hr;
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: CreateDirectDraw()
// Desc: Create the DirectDraw interface
//-----------------------------------------------------------------------------
HRESULT CD3DFramework::CreateDirectDraw( GUID* pDriverGUID, DWORD dwFlags )
{
// Create the DirectDraw interface, and query for the DD4 interface
LPDIRECTDRAW pDD;
if( FAILED( DirectDrawCreate( pDriverGUID, &pDD, NULL ) ) )
{
DEBUG_MSG( TEXT("Could not create DirectDraw") );
return D3DFWERR_NODIRECTDRAW;
}
if( FAILED( pDD->QueryInterface( IID_IDirectDraw4, (VOID**)&m_pDD ) ) )
{
pDD->Release();
DEBUG_MSG( TEXT("Couldn't query for DirectDraw4") );
return D3DFWERR_NODIRECTDRAW;
}
pDD->Release();
// Set the Windows cooperative level
DWORD dwCoopFlags = DDSCL_NORMAL;
if( m_bIsFullscreen )
dwCoopFlags = DDSCL_ALLOWREBOOT|DDSCL_EXCLUSIVE|DDSCL_FULLSCREEN;
// By defualt, set the flag to allow D3D to optimize floating point calcs
if( 0L == ( dwFlags & D3DFW_NO_FPUSETUP ) )
dwCoopFlags |= DDSCL_FPUSETUP;
if( FAILED( m_pDD->SetCooperativeLevel( m_hWnd, dwCoopFlags ) ) )
{
DEBUG_MSG( TEXT("Couldn't set coop level") );
return D3DFWERR_COULDNTSETCOOPLEVEL;
}
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: CreateDirect3D()
// Desc: Create the Direct3D interface
//-----------------------------------------------------------------------------
HRESULT CD3DFramework::CreateDirect3D( GUID* pDeviceGUID, DWORD dwFlags )
{
// Query DirectDraw for access to Direct3D
if( FAILED( m_pDD->QueryInterface( IID_IDirect3D3, (VOID**)&m_pD3D ) ) )
{
DEBUG_MSG( TEXT("Couldn't query the Direct3D interface") );
return D3DFWERR_NODIRECT3D;
}
// Use the FindDevice() method to test if the requested device
// exists, and if so, take note of what memory type it takes.
D3DFINDDEVICERESULT devResult;
D3DFINDDEVICESEARCH devSearch;
ZeroMemory( &devResult, sizeof(D3DFINDDEVICERESULT) );
ZeroMemory( &devSearch, sizeof(D3DFINDDEVICESEARCH) );
devResult.dwSize = sizeof(D3DFINDDEVICERESULT);
devSearch.dwSize = sizeof(D3DFINDDEVICESEARCH);
devSearch.dwFlags = D3DFDS_GUID;
CopyMemory( &devSearch.guid, pDeviceGUID, sizeof(GUID) );
if( FAILED( m_pD3D->FindDevice( &devSearch, &devResult ) ) )
{
DEBUG_MSG( TEXT("Couldn't find the specified device") );
return D3DFWERR_NODIRECT3D;
}
// Whether device is SW or HW, get the devicedesc, and the defualt memtype
if( 0L == devResult.ddHwDesc.dwFlags )
{
m_dwDeviceMemType = DDSCAPS_SYSTEMMEMORY;
memcpy( &m_ddDeviceDesc, &devResult.ddSwDesc, sizeof(D3DDEVICEDESC) );
}
else
{
m_dwDeviceMemType = DDSCAPS_VIDEOMEMORY;
memcpy( &m_ddDeviceDesc, &devResult.ddHwDesc, sizeof(D3DDEVICEDESC) );
}
// Using the device GUID, let's enumerate a format for our z-buffer, in
// case we later decide to create one.
ZeroMemory( &m_ddpfZBuffer, sizeof(DDPIXELFORMAT) );
if( dwFlags & D3DFW_STENCILBUFFER )
m_ddpfZBuffer.dwFlags = DDPF_ZBUFFER | DDPF_STENCILBUFFER;
else
m_ddpfZBuffer.dwFlags = DDPF_ZBUFFER;
// Get an appropiate pixel format from enumeration of the formats.
m_pD3D->EnumZBufferFormats( *pDeviceGUID, EnumZBufferFormatsCallback,
(VOID*)&m_ddpfZBuffer );
if( sizeof(DDPIXELFORMAT) != m_ddpfZBuffer.dwSize )
{
DEBUG_MSG( TEXT("Device doesn't support requested zbuffer format") );
return D3DFWERR_NOZBUFFER;
}
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: CreateBuffers()
// Desc: Creates the primary and (optional) backbuffer for rendering.
// Windowed mode and fullscreen mode are handled differently.
//-----------------------------------------------------------------------------
HRESULT CD3DFramework::CreateBuffers( DDSURFACEDESC2* pddsd, DWORD dwFlags )
{
HRESULT hr;
if( dwFlags & D3DFW_FULLSCREEN )
{
// Get the dimensions of the viewport and screen bounds
// Store the rectangle which contains the renderer
SetRect( &m_rcViewportRect, 0, 0, pddsd->dwWidth, pddsd->dwHeight );
memcpy( &m_rcScreenRect, &m_rcViewportRect, sizeof(RECT) );
m_dwRenderWidth = m_rcViewportRect.right;
m_dwRenderHeight = m_rcViewportRect.bottom;
// Set the display mode to the requested dimensions. Check for
// 320x200x8 modes, and set flag to avoid using ModeX
DWORD dwModeFlags = 0;
if( (320==m_dwRenderWidth) && (200==m_dwRenderHeight) &&
(8==pddsd->ddpfPixelFormat.dwRGBBitCount) )
dwModeFlags |= DDSDM_STANDARDVGAMODE;
if( FAILED( m_pDD->SetDisplayMode( m_dwRenderWidth, m_dwRenderHeight,
pddsd->ddpfPixelFormat.dwRGBBitCount,
pddsd->dwRefreshRate, dwModeFlags ) ) )
{
DEBUG_MSG( TEXT("Can't set display mode") );
return D3DFWERR_BADDISPLAYMODE;
}
// Create the primary surface
DDSURFACEDESC2 ddsd;
D3DUtil_InitSurfaceDesc( ddsd, DDSD_CAPS );
ddsd.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE | DDSCAPS_3DDEVICE;
// With no backbuffer, the primary becomes the render target
if( dwFlags & D3DFW_BACKBUFFER )
{
ddsd.dwFlags |= DDSD_BACKBUFFERCOUNT;
ddsd.ddsCaps.dwCaps |= DDSCAPS_FLIP | DDSCAPS_COMPLEX;
ddsd.dwBackBufferCount = 1;
}
if( FAILED( hr = m_pDD->CreateSurface( &ddsd, &m_pddsFrontBuffer, NULL ) ) )
{
DEBUG_MSG( TEXT("Error: Can't create primary surface") );
if( hr != DDERR_OUTOFVIDEOMEMORY )
return D3DFWERR_NOPRIMARY;
DEBUG_MSG( TEXT("Error: Out of video memory") );
return DDERR_OUTOFVIDEOMEMORY;
}
// Get the backbuffer. For fullscreen mode, the backbuffer was created
// along with the primary, but windowed mode still needs to create one.
if( dwFlags & D3DFW_BACKBUFFER )
{
// Get a ptr to the back buffer, which will be our render target
DDSCAPS2 ddscaps;
ddscaps.dwCaps = DDSCAPS_BACKBUFFER;
if( FAILED( hr = m_pddsFrontBuffer->GetAttachedSurface( &ddscaps,
&m_pddsBackBuffer ) ) )
{
DEBUG_MSG( TEXT("Error: Can't get/create the backbuffer") );
if( hr != DDERR_OUTOFVIDEOMEMORY )
return D3DFWERR_NOBACKBUFFER;
DEBUG_MSG( TEXT("Error: Out of video memory") );
return DDERR_OUTOFVIDEOMEMORY;
}
}
}
else // Set up buffers for windowed rendering
{
// Get the dimensions of the viewport and screen bounds
GetClientRect( m_hWnd, &m_rcViewportRect );
GetClientRect( m_hWnd, &m_rcScreenRect );
ClientToScreen( m_hWnd, (POINT*)&m_rcScreenRect.left );
ClientToScreen( m_hWnd, (POINT*)&m_rcScreenRect.right );
m_dwRenderWidth = m_rcViewportRect.right;
m_dwRenderHeight = m_rcViewportRect.bottom;
// Create the primary surface
DDSURFACEDESC2 ddsd;
D3DUtil_InitSurfaceDesc( ddsd, DDSD_CAPS );
ddsd.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE;
// With no backbuffer, the primary becomes the render target
if( 0L == ( dwFlags & D3DFW_BACKBUFFER ) )
ddsd.ddsCaps.dwCaps |= DDSCAPS_3DDEVICE;
if( FAILED( hr = m_pDD->CreateSurface( &ddsd, &m_pddsFrontBuffer, NULL ) ) )
{
DEBUG_MSG( TEXT("Error: Can't create primary surface") );
if( hr != DDERR_OUTOFVIDEOMEMORY )
return D3DFWERR_NOPRIMARY;
DEBUG_MSG( TEXT("Error: Out of video memory") );
return DDERR_OUTOFVIDEOMEMORY;
}
// If in windowed-mode, create a clipper object
LPDIRECTDRAWCLIPPER pcClipper;
if( FAILED( hr = m_pDD->CreateClipper( 0, &pcClipper, NULL ) ) )
{
DEBUG_MSG( TEXT("Error: Couldn't create clipper") );
return D3DFWERR_NOCLIPPER;
}
// Associate the clipper with the window
pcClipper->SetHWnd( 0, m_hWnd );
m_pddsFrontBuffer->SetClipper( pcClipper );
SAFE_RELEASE( pcClipper );
// Get the backbuffer. For fullscreen mode, the backbuffer was created
// along with the primary, but windowed mode still needs to create one.
if( dwFlags & D3DFW_BACKBUFFER )
{
// Create the back buffer (the render target)
ddsd.dwFlags = DDSD_WIDTH | DDSD_HEIGHT | DDSD_CAPS;
ddsd.dwWidth = m_dwRenderWidth;
ddsd.dwHeight = m_dwRenderHeight;
ddsd.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN | DDSCAPS_3DDEVICE;
if( FAILED( hr = m_pDD->CreateSurface( &ddsd, &m_pddsBackBuffer, NULL ) ) )
{
DEBUG_MSG( TEXT("Error: Couldn't create the backbuffer") );
if( hr != DDERR_OUTOFVIDEOMEMORY )
return D3DFWERR_NOBACKBUFFER;
DEBUG_MSG( TEXT("Error: Out of video memory") );
return DDERR_OUTOFVIDEOMEMORY;
}
}
else // For rendering without a backbuffer
{
ClientToScreen( m_hWnd, (POINT*)&m_rcViewportRect.left );
ClientToScreen( m_hWnd, (POINT*)&m_rcViewportRect.right );
}
}
// Set up backbuffer ptr and ref counts
if( dwFlags & D3DFW_BACKBUFFER )
m_pddsRenderTarget = m_pddsBackBuffer;
else
m_pddsRenderTarget = m_pddsFrontBuffer;
m_pddsRenderTarget->AddRef();
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: CreateZBuffer()
// Desc: Internal function called by Create() to make and attach a zbuffer
// to the renderer
//-----------------------------------------------------------------------------
HRESULT CD3DFramework::CreateZBuffer()
{
HRESULT hr;
// Check if the device supports z-bufferless hidden surface removal. If so,
// we don't really need a z-buffer
DWORD dwRasterCaps = m_ddDeviceDesc.dpcTriCaps.dwRasterCaps;
if( dwRasterCaps & D3DPRASTERCAPS_ZBUFFERLESSHSR )
return S_OK;
// Get z-buffer dimensions from the render target
// Setup the surface desc for the z-buffer.
DDSURFACEDESC2 ddsd;
D3DUtil_InitSurfaceDesc( ddsd, DDSD_WIDTH | DDSD_HEIGHT | DDSD_CAPS |
DDSD_PIXELFORMAT );
ddsd.ddsCaps.dwCaps = DDSCAPS_ZBUFFER | m_dwDeviceMemType;
ddsd.dwWidth = m_dwRenderWidth;
ddsd.dwHeight = m_dwRenderHeight;
memcpy( &ddsd.ddpfPixelFormat, &m_ddpfZBuffer, sizeof(DDPIXELFORMAT) );
// Create and attach a z-buffer
if( FAILED( hr = m_pDD->CreateSurface( &ddsd, &m_pddsZBuffer, NULL ) ) )
{
DEBUG_MSG( TEXT("Error: Couldn't create a ZBuffer surface") );
if( hr != DDERR_OUTOFVIDEOMEMORY )
return D3DFWERR_NOZBUFFER;
DEBUG_MSG( TEXT("Error: Out of video memory") );
return DDERR_OUTOFVIDEOMEMORY;
}
if( FAILED( m_pddsRenderTarget->AddAttachedSurface( m_pddsZBuffer ) ) )
{
DEBUG_MSG( TEXT("Error: Couldn't attach zbuffer to render surface") );
return D3DFWERR_NOZBUFFER;
}
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: Create3DDevice()
// Desc: Creates the 3D device for the render target
//-----------------------------------------------------------------------------
HRESULT CD3DFramework::Create3DDevice( GUID* pDeviceGUID )
{
// Check that we are NOT in a palettized display. That case will fail,
// since the framework doesn't use palettes.
DDSURFACEDESC2 ddsd;
ddsd.dwSize = sizeof(DDSURFACEDESC2);
m_pDD->GetDisplayMode( &ddsd );
if( ddsd.ddpfPixelFormat.dwRGBBitCount <= 8 )
return D3DFWERR_INVALIDMODE;
// Create the device
if( FAILED( m_pD3D->CreateDevice( *pDeviceGUID, m_pddsRenderTarget,
&m_pd3dDevice, NULL ) ) )
{
DEBUG_MSG( TEXT("Couldn't create the D3DDevice") );
return D3DFWERR_NO3DDEVICE;
}
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: CreateViewport()
// Desc: Create the D3D viewport used by the renderer.
//-----------------------------------------------------------------------------
HRESULT CD3DFramework::CreateViewport()
{
// Set up the viewport data parameters
HRESULT hr;
D3DVIEWPORT2 vdData;
D3DUtil_InitViewport( vdData, m_dwRenderWidth, m_dwRenderHeight );
// Create the viewport
if( FAILED( m_pD3D->CreateViewport( &m_pvViewport, NULL ) ) )
{
DEBUG_MSG( TEXT("Error: Couldn't create a viewport") );
return D3DFWERR_NOVIEWPORT;
}
// Associate the viewport with the D3DDEVICE object
if( FAILED( hr = m_pd3dDevice->AddViewport( m_pvViewport ) ) )
{
DEBUG_MSG( TEXT("Error: Couldn't add the viewport") );
return D3DFWERR_NOVIEWPORT;
}
// Set the parameters to the new viewport
if( FAILED( m_pvViewport->SetViewport2( &vdData ) ) )
{
DEBUG_MSG( TEXT("Error: Couldn't set the viewport data") );
return D3DFWERR_NOVIEWPORT;
}
// Finally, set the current viewport for the current device
if( FAILED( m_pd3dDevice->SetCurrentViewport( m_pvViewport ) ) )
{
DEBUG_MSG( TEXT("Error: Couldn't set current viewport to device") );
return D3DFWERR_NOVIEWPORT;
}
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: ShowFrame()
// Desc: Show the frame on the primary surface, via a blt or a flip.
//-----------------------------------------------------------------------------
HRESULT CD3DFramework::ShowFrame()
{
if( NULL == m_pddsFrontBuffer )
return D3DFWERR_NOTINITIALIZED;
// Check for a backbuffer. If no backbuffer exists, then we have nothing to
// do. However, to be consistent let's check for lost surfaces
if( NULL == m_pddsBackBuffer )
return m_pddsFrontBuffer->IsLost();
// If we are in fullscreen mode perform a flip.
if( m_bIsFullscreen )
return m_pddsFrontBuffer->Flip( NULL, DDFLIP_WAIT );
// Else, we are in windowed mode, so perform a blit.
return m_pddsFrontBuffer->Blt( &m_rcScreenRect, m_pddsBackBuffer,
&m_rcViewportRect, DDBLT_WAIT, NULL );
}
//-----------------------------------------------------------------------------
// Name: FlipToGDISurface()
// Desc: Puts the GDI surface in front of the primary, so that dialog
// boxes and other windows drawing funcs may happen.
//-----------------------------------------------------------------------------
HRESULT CD3DFramework::FlipToGDISurface( BOOL bDrawFrame )
{
if( m_pDD && m_bIsFullscreen )
{
m_pDD->FlipToGDISurface();
if( bDrawFrame )
{
DrawMenuBar( m_hWnd );
RedrawWindow( m_hWnd, NULL, NULL, RDW_FRAME );
}
}
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: RestoreSurfaces()
// Desc: Checks for lost surfaces and restores them if lost. Note: Don't
// restore render surface, since it's just a duplicate ptr.
//-----------------------------------------------------------------------------
HRESULT CD3DFramework::RestoreSurfaces()
{
// Check/restore the primary surface
if( m_pddsFrontBuffer )
if( m_pddsFrontBuffer->IsLost() )
m_pddsFrontBuffer->Restore();
// Check/restore the back buffer
if( m_pddsBackBuffer )
if( m_pddsBackBuffer->IsLost() )
m_pddsBackBuffer->Restore();
// Check/restore the z-buffer surface
if( m_pddsZBuffer )
if( m_pddsZBuffer->IsLost() )
m_pddsZBuffer->Restore();
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: Move()
// Desc: Moves the screen rect for windowed renderers
//-----------------------------------------------------------------------------
VOID CD3DFramework::Move( INT x, INT y )
{
if( FALSE == m_bIsFullscreen )
{
SetRect( &m_rcScreenRect, x, y,
x + m_dwRenderWidth, y + m_dwRenderHeight );
// If we have no backbuffer, then update viewport rect as well
if( NULL == m_pddsBackBuffer )
CopyMemory( &m_rcViewportRect, &m_rcScreenRect, sizeof(RECT) );
}
}
//-----------------------------------------------------------------------------
// Name: ChangeRenderTarget()
// Desc: Wrapper for the IDirect3DDevice::SetRenderTarget() function, which
// adds functionality to handle an attached z-buffer. Note that this
// function does NOT alter the current viewport
//-----------------------------------------------------------------------------
HRESULT CD3DFramework::ChangeRenderTarget( LPDIRECTDRAWSURFACE4 pddsNewTarget )
{
if( NULL == pddsNewTarget )
return E_INVALIDARG;
// Get the new render target dimensions
DDSURFACEDESC2 ddsd;
D3DUtil_InitSurfaceDesc( ddsd );
pddsNewTarget->GetSurfaceDesc( &ddsd );
m_dwRenderWidth = ddsd.dwWidth;
m_dwRenderHeight = ddsd.dwHeight;
// If a z-buffer is attached, delete and recreate it
if( NULL != m_pddsZBuffer )
{
// Remove the old z-buffer
m_pddsRenderTarget->DeleteAttachedSurface( 0, m_pddsZBuffer );
SAFE_RELEASE( m_pddsZBuffer );
// Keep track of reference counts
SAFE_RELEASE( m_pddsRenderTarget );
m_pddsRenderTarget = pddsNewTarget;
m_pddsRenderTarget->AddRef();
// Create the new z-buffer
if( FAILED( CreateZBuffer() ) )
{
DEBUG_MSG( TEXT("ChangeRenderTarget() - zbuffer create failed") );
return D3DFWERR_NOZBUFFER;
}
}
else
{
// With no z-buffer, we just do accounting on the reference counts
SAFE_RELEASE( m_pddsRenderTarget );
m_pddsRenderTarget = pddsNewTarget;
m_pddsRenderTarget->AddRef();
}
// Finally, perform the set render target call
if( FAILED( m_pd3dDevice->SetRenderTarget( m_pddsRenderTarget, 0 ) ) )
{
return D3DFWERR_NORENDERTARGET;
}
return S_OK;
}

View file

@ -1,136 +0,0 @@
//-----------------------------------------------------------------------------
// File: D3DFrame.h
//
// Desc: Class to manage the Direct3D environment objects such as buffers,
// viewports, and 3D devices.
//
// The class is initialized with the Initialize() function, after which
// the Get????() functions can be used to access the objects needed for
// rendering. If the device or display needs to be changed, the
// ChangeDevice() function can be called. If the display window is moved
// the changes need to be reported with the Move() function.
//
// After rendering a frame, the ShowFrame() function filps or blits the
// backbuffer contents to the primary. If surfaces are lost, they can be
// restored with the RestoreSurfaces() function. Finally, if normal
// Windows output is needed, the FlipToGDISurface() provides a GDI
// surface to draw on.
//
//
// Copyright (C) 1997 Microsoft Corporation. All rights reserved
//-----------------------------------------------------------------------------
#ifndef D3DFRAME_H
#define D3DFRAME_H
#include <ddraw.h>
#include <d3d.h>
//-----------------------------------------------------------------------------
// Name: CD3DFramework
// Desc: The Direct3D sample framework class. Maintains the D3D surfaces,
// device, and viewport used for 3D rendering.
//-----------------------------------------------------------------------------
class CD3DFramework
{
// Internal variables for the framework class
HWND m_hWnd; // The window object
BOOL m_bIsFullscreen; // Fullscreen vs. windowed
RECT m_rcViewportRect; // Offscreen rect for VPort
LPDIRECTDRAWSURFACE4 m_pddsFrontBuffer; // The primary surface
LPDIRECTDRAWSURFACE4 m_pddsBackBuffer; // The backbuffer surface
LPDIRECTDRAWSURFACE4 m_pddsRenderTarget; // The render target surface
LPDIRECTDRAWSURFACE4 m_pddsZBuffer; // The zbuffer surface
LPDIRECT3DDEVICE3 m_pd3dDevice; // The D3D device
LPDIRECT3DVIEWPORT3 m_pvViewport; // The D3D viewport
LPDIRECTDRAW4 m_pDD; // The DirectDraw object
LPDIRECT3D3 m_pD3D; // The Direct3D object
D3DDEVICEDESC m_ddDeviceDesc;
DWORD m_dwDeviceMemType;
DDPIXELFORMAT m_ddpfZBuffer; // Enumerated zbuffer format
// Internal functions for the framework class
HRESULT CreateViewport();
HRESULT Create3DDevice( GUID* );
HRESULT CreateZBuffer();
HRESULT CreateBuffers( DDSURFACEDESC2*, DWORD );
HRESULT CreateDirectDraw( GUID*, DWORD );
HRESULT CreateDirect3D( GUID*, DWORD );
HRESULT CreateEnvironment( GUID*, GUID*, DDSURFACEDESC2*, DWORD );
public:
DWORD m_dwRenderWidth; // Dimensions of the render target
DWORD m_dwRenderHeight;
RECT m_rcScreenRect; // Screen rect for window
// Access functions for DirectX objects
LPDIRECTDRAW4 GetDirectDraw() { return m_pDD; }
LPDIRECT3D3 GetDirect3D() { return m_pD3D; }
LPDIRECT3DDEVICE3 GetD3DDevice() { return m_pd3dDevice; }
LPDIRECT3DVIEWPORT3 GetViewport() { return m_pvViewport; }
LPDIRECTDRAWSURFACE4 GetFrontBuffer() { return m_pddsFrontBuffer; }
LPDIRECTDRAWSURFACE4 GetBackBuffer() { return m_pddsBackBuffer; }
LPDIRECTDRAWSURFACE4 GetRenderSurface() { return m_pddsRenderTarget; }
// Functions to aid rendering
HRESULT RestoreSurfaces();
HRESULT ShowFrame();
HRESULT FlipToGDISurface( BOOL bDrawFrame );
// Functions for managing screen and viewport bounds
BOOL IsFullscreen() { return m_bIsFullscreen; }
RECT* GetViewportRect() { return &m_rcViewportRect; }
VOID Move( INT x, INT y );
// Functions to support sprite-based rendering
HRESULT ChangeRenderTarget( LPDIRECTDRAWSURFACE4 pddsNewTarget );
// Creates the Framework
HRESULT Initialize( HWND hWnd, GUID* pDriverGUID, GUID* pDeviceGUID,
DDSURFACEDESC2* pddsd, DWORD dwFlags );
HRESULT DestroyObjects();
CD3DFramework();
~CD3DFramework();
};
//-----------------------------------------------------------------------------
// Flags used for the Initialize() method of a CD3DFramework object
//-----------------------------------------------------------------------------
#define D3DFW_FULLSCREEN 0x00000001 // Use fullscreen mode
#define D3DFW_BACKBUFFER 0x00000002 // Create and use a backbuffer
#define D3DFW_ZBUFFER 0x00000004 // Create and use a zbuffer
#define D3DFW_STENCILBUFFER 0x00000008 // Use a z-buffer w/stenciling
#define D3DFW_NO_FPUSETUP 0x00000010 // Don't use default DDSCL_FPUSETUP flag
//-----------------------------------------------------------------------------
// Errors that the Initialize() and ChangeDriver() calls may return
//-----------------------------------------------------------------------------
#define D3DFWERR_INITIALIZATIONFAILED 0x82000000
#define D3DFWERR_NODIRECTDRAW 0x82000001
#define D3DFWERR_COULDNTSETCOOPLEVEL 0x82000002
#define D3DFWERR_NODIRECT3D 0x82000003
#define D3DFWERR_NO3DDEVICE 0x82000004
#define D3DFWERR_NOZBUFFER 0x82000005
#define D3DFWERR_NOVIEWPORT 0x82000006
#define D3DFWERR_NOPRIMARY 0x82000007
#define D3DFWERR_NOCLIPPER 0x82000008
#define D3DFWERR_BADDISPLAYMODE 0x82000009
#define D3DFWERR_NOBACKBUFFER 0x8200000a
#define D3DFWERR_NONZEROREFCOUNT 0x8200000b
#define D3DFWERR_NORENDERTARGET 0x8200000c
#define D3DFWERR_INVALIDMODE 0x8200000d
#define D3DFWERR_NOTINITIALIZED 0x8200000e
#endif // D3DFRAME_H

View file

@ -1,341 +0,0 @@
//-----------------------------------------------------------------------------
// File: D3DMath.cpp
//
// Desc: Shortcut macros and functions for using DX objects
//
//
// Copyright (c) 1997-1998 Microsoft Corporation. All rights reserved
//-----------------------------------------------------------------------------
#define D3D_OVERLOADS
#include <math.h>
#include <stdio.h>
#include "D3DMath.h"
//-----------------------------------------------------------------------------
// Name: D3DMath_MatrixMultiply()
// Desc: Does the matrix operation: [Q] = [A] * [B].
//-----------------------------------------------------------------------------
VOID D3DMath_MatrixMultiply( D3DMATRIX& q, D3DMATRIX& a, D3DMATRIX& b )
{
FLOAT* pA = (FLOAT*)&a;
FLOAT* pB = (FLOAT*)&b;
FLOAT pM[16];
ZeroMemory( pM, sizeof(D3DMATRIX) );
for( WORD i=0; i<4; i++ )
for( WORD j=0; j<4; j++ )
for( WORD k=0; k<4; k++ )
pM[4*i+j] += pA[4*k+j] * pB[4*i+k];
memcpy( &q, pM, sizeof(D3DMATRIX) );
}
//-----------------------------------------------------------------------------
// Name: D3DMath_MatrixInvert()
// Desc: Does the matrix operation: [Q] = inv[A]. Note: this function only
// works for matrices with [0 0 0 1] for the 4th column.
//-----------------------------------------------------------------------------
HRESULT D3DMath_MatrixInvert( D3DMATRIX& q, D3DMATRIX& a )
{
if( fabs(a._44 - 1.0f) > .001f)
return E_INVALIDARG;
if( fabs(a._14) > .001f || fabs(a._24) > .001f || fabs(a._34) > .001f )
return E_INVALIDARG;
FLOAT fDetInv = 1.0f / ( a._11 * ( a._22 * a._33 - a._23 * a._32 ) -
a._12 * ( a._21 * a._33 - a._23 * a._31 ) +
a._13 * ( a._21 * a._32 - a._22 * a._31 ) );
q._11 = fDetInv * ( a._22 * a._33 - a._23 * a._32 );
q._12 = -fDetInv * ( a._12 * a._33 - a._13 * a._32 );
q._13 = fDetInv * ( a._12 * a._23 - a._13 * a._22 );
q._14 = 0.0f;
q._21 = -fDetInv * ( a._21 * a._33 - a._23 * a._31 );
q._22 = fDetInv * ( a._11 * a._33 - a._13 * a._31 );
q._23 = -fDetInv * ( a._11 * a._23 - a._13 * a._21 );
q._24 = 0.0f;
q._31 = fDetInv * ( a._21 * a._32 - a._22 * a._31 );
q._32 = -fDetInv * ( a._11 * a._32 - a._12 * a._31 );
q._33 = fDetInv * ( a._11 * a._22 - a._12 * a._21 );
q._34 = 0.0f;
q._41 = -( a._41 * q._11 + a._42 * q._21 + a._43 * q._31 );
q._42 = -( a._41 * q._12 + a._42 * q._22 + a._43 * q._32 );
q._43 = -( a._41 * q._13 + a._42 * q._23 + a._43 * q._33 );
q._44 = 1.0f;
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: D3DMath_VectorMatrixMultiply()
// Desc: Multiplies a vector by a matrix
//-----------------------------------------------------------------------------
HRESULT D3DMath_VectorMatrixMultiply( D3DVECTOR& vDest, D3DVECTOR& vSrc,
D3DMATRIX& mat)
{
FLOAT x = vSrc.x*mat._11 + vSrc.y*mat._21 + vSrc.z* mat._31 + mat._41;
FLOAT y = vSrc.x*mat._12 + vSrc.y*mat._22 + vSrc.z* mat._32 + mat._42;
FLOAT z = vSrc.x*mat._13 + vSrc.y*mat._23 + vSrc.z* mat._33 + mat._43;
FLOAT w = vSrc.x*mat._14 + vSrc.y*mat._24 + vSrc.z* mat._34 + mat._44;
if( fabs( w ) < g_EPSILON )
return E_INVALIDARG;
vDest.x = x/w;
vDest.y = y/w;
vDest.z = z/w;
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: D3DMath_VertexMatrixMultiply()
// Desc: Multiplies a vertex by a matrix
//-----------------------------------------------------------------------------
HRESULT D3DMath_VertexMatrixMultiply( D3DVERTEX& vDest, D3DVERTEX& vSrc,
D3DMATRIX& mat )
{
HRESULT hr;
D3DVECTOR* pSrcVec = (D3DVECTOR*)&vSrc.x;
D3DVECTOR* pDestVec = (D3DVECTOR*)&vDest.x;
if( SUCCEEDED( hr = D3DMath_VectorMatrixMultiply( *pDestVec, *pSrcVec,
mat ) ) )
{
pSrcVec = (D3DVECTOR*)&vSrc.nx;
pDestVec = (D3DVECTOR*)&vDest.nx;
hr = D3DMath_VectorMatrixMultiply( *pDestVec, *pSrcVec, mat );
}
return hr;
}
//-----------------------------------------------------------------------------
// Name: D3DMath_QuaternionFromRotation()
// Desc: Converts a normalized axis and angle to a unit quaternion.
//-----------------------------------------------------------------------------
VOID D3DMath_QuaternionFromRotation( FLOAT& x, FLOAT& y, FLOAT& z, FLOAT& w,
D3DVECTOR& v, FLOAT fTheta )
{
x = (FLOAT)sin(fTheta/2) * v.x;
y = (FLOAT)sin(fTheta/2) * v.y;
z = (FLOAT)sin(fTheta/2) * v.z;
w = (FLOAT)cos(fTheta/2);
}
//-----------------------------------------------------------------------------
// Name: D3DMath_RotationFromQuaternion()
// Desc: Converts a normalized axis and angle to a unit quaternion.
//-----------------------------------------------------------------------------
VOID D3DMath_RotationFromQuaternion( D3DVECTOR& v, FLOAT& fTheta,
FLOAT x, FLOAT y, FLOAT z, FLOAT w )
{
fTheta = (FLOAT)( acos(w) * 2 );
v.x = (FLOAT)( x / sin(fTheta/2) );
v.y = (FLOAT)( y / sin(fTheta/2) );
v.z = (FLOAT)( z / sin(fTheta/2) );
}
//-----------------------------------------------------------------------------
// Name: D3DMath_QuaternionFromAngles()
// Desc: Converts euler angles to a unit quaternion.
//-----------------------------------------------------------------------------
VOID D3DMath_QuaternionFromAngles( FLOAT& x, FLOAT& y, FLOAT& z, FLOAT& w,
FLOAT fYaw, FLOAT fPitch, FLOAT fRoll )
{
FLOAT fSinYaw = (FLOAT)sin(fYaw/2);
FLOAT fSinPitch = (FLOAT)sin(fPitch/2);
FLOAT fSinRoll = (FLOAT)sin(fRoll/2);
FLOAT fCosYaw = (FLOAT)cos(fYaw/2);
FLOAT fCosPitch = (FLOAT)cos(fPitch/2);
FLOAT fCosRoll = (FLOAT)cos(fRoll/2);
x = fSinRoll * fCosPitch * fCosYaw - fCosRoll * fSinPitch * fSinYaw;
y = fCosRoll * fSinPitch * fCosYaw + fSinRoll * fCosPitch * fSinYaw;
z = fCosRoll * fCosPitch * fSinYaw - fSinRoll * fSinPitch * fCosYaw;
w = fCosRoll * fCosPitch * fCosYaw + fSinRoll * fSinPitch * fSinYaw;
}
//-----------------------------------------------------------------------------
// Name: D3DMath_MatrixFromQuaternion()
// Desc: Converts a unit quaternion into a rotation matrix.
//-----------------------------------------------------------------------------
VOID D3DMath_MatrixFromQuaternion( D3DMATRIX& mat, FLOAT x, FLOAT y, FLOAT z,
FLOAT w )
{
FLOAT xx = x*x; FLOAT yy = y*y; FLOAT zz = z*z;
FLOAT xy = x*y; FLOAT xz = x*z; FLOAT yz = y*z;
FLOAT wx = w*x; FLOAT wy = w*y; FLOAT wz = w*z;
mat._11 = 1 - 2 * ( yy + zz );
mat._12 = 2 * ( xy - wz );
mat._13 = 2 * ( xz + wy );
mat._21 = 2 * ( xy + wz );
mat._22 = 1 - 2 * ( xx + zz );
mat._23 = 2 * ( yz - wx );
mat._31 = 2 * ( xz - wy );
mat._32 = 2 * ( yz + wx );
mat._33 = 1 - 2 * ( xx + yy );
mat._14 = mat._24 = mat._34 = 0.0f;
mat._41 = mat._42 = mat._43 = 0.0f;
mat._44 = 1.0f;
}
//-----------------------------------------------------------------------------
// Name: D3DMath_QuaternionFromMatrix()
// Desc: Converts a rotation matrix into a unit quaternion.
//-----------------------------------------------------------------------------
VOID D3DMath_QuaternionFromMatrix( FLOAT& x, FLOAT& y, FLOAT& z, FLOAT& w,
D3DMATRIX& mat )
{
if( mat._11 + mat._22 + mat._33 > 0.0f )
{
FLOAT s = (FLOAT)sqrt( mat._11 + mat._22 + mat._33 + mat._44 );
x = (mat._23-mat._32) / (2*s);
y = (mat._31-mat._13) / (2*s);
z = (mat._12-mat._21) / (2*s);
w = 0.5f * s;
}
else
{
}
FLOAT xx = x*x; FLOAT yy = y*y; FLOAT zz = z*z;
FLOAT xy = x*y; FLOAT xz = x*z; FLOAT yz = y*z;
FLOAT wx = w*x; FLOAT wy = w*y; FLOAT wz = w*z;
mat._11 = 1 - 2 * ( yy + zz );
mat._12 = 2 * ( xy - wz );
mat._13 = 2 * ( xz + wy );
mat._21 = 2 * ( xy + wz );
mat._22 = 1 - 2 * ( xx + zz );
mat._23 = 2 * ( yz - wx );
mat._31 = 2 * ( xz - wy );
mat._32 = 2 * ( yz + wx );
mat._33 = 1 - 2 * ( xx + yy );
mat._14 = mat._24 = mat._34 = 0.0f;
mat._41 = mat._42 = mat._43 = 0.0f;
mat._44 = 1.0f;
}
//-----------------------------------------------------------------------------
// Name: D3DMath_QuaternionMultiply()
// Desc: Mulitples two quaternions together as in {Q} = {A} * {B}.
//-----------------------------------------------------------------------------
VOID D3DMath_QuaternionMultiply( FLOAT& Qx, FLOAT& Qy, FLOAT& Qz, FLOAT& Qw,
FLOAT Ax, FLOAT Ay, FLOAT Az, FLOAT Aw,
FLOAT Bx, FLOAT By, FLOAT Bz, FLOAT Bw )
{
FLOAT Dx = Bw*Ax + Bx*Aw + By*Az + Bz*Ay;
FLOAT Dy = Bw*Ay + By*Aw + Bz*Ax + Bx*Az;
FLOAT Dz = Bw*Az + Bz*Aw + Bx*Ay + By*Ax;
FLOAT Dw = Bw*Aw + Bx*Ax + By*Ay + Bz*Az;
Qx = Dx; Qy = Dy; Qz = Dz; Qw = Dw;
}
//-----------------------------------------------------------------------------
// Name: D3DMath_SlerpQuaternions()
// Desc: Compute a quaternion which is the spherical linear interpolation
// between two other quaternions by dvFraction.
//-----------------------------------------------------------------------------
VOID D3DMath_QuaternionSlerp( FLOAT& Qx, FLOAT& Qy, FLOAT& Qz, FLOAT& Qw,
FLOAT Ax, FLOAT Ay, FLOAT Az, FLOAT Aw,
FLOAT Bx, FLOAT By, FLOAT Bz, FLOAT Bw,
FLOAT fAlpha )
{
FLOAT fScale1;
FLOAT fScale2;
// Compute dot product, aka cos(theta):
FLOAT fCosTheta = Ax*Bx + Ay*By + Az*Bz + Aw*Bw;
if( fCosTheta < 0.0f )
{
// Flip start quaternion
Ax = -Ax; Ay = -Ay; Ax = -Az; Aw = -Aw;
fCosTheta = -fCosTheta;
}
if( fCosTheta + 1.0f > 0.05f )
{
// If the quaternions are close, use linear interploation
if( 1.0f - fCosTheta < 0.05f )
{
fScale1 = 1.0f - fAlpha;
fScale2 = fAlpha;
}
else // Otherwise, do spherical interpolation
{
FLOAT fTheta = (FLOAT)acos( fCosTheta );
FLOAT fSinTheta = (FLOAT)sin( fTheta );
fScale1 = (FLOAT)sin( fTheta * (1.0f-fAlpha) ) / fSinTheta;
fScale2 = (FLOAT)sin( fTheta * fAlpha ) / fSinTheta;
}
}
else
{
Bx = -Ay;
By = Ax;
Bz = -Aw;
Bw = Az;
fScale1 = (FLOAT)sin( g_PI * (0.5f - fAlpha) );
fScale2 = (FLOAT)sin( g_PI * fAlpha );
}
Qx = fScale1 * Ax + fScale2 * Bx;
Qy = fScale1 * Ay + fScale2 * By;
Qz = fScale1 * Az + fScale2 * Bz;
Qw = fScale1 * Aw + fScale2 * Bw;
}

View file

@ -1,85 +0,0 @@
//-----------------------------------------------------------------------------
// File: D3DMath.h
//
// Desc: Math functions and shortcuts for Direct3D programming.
//
//
// Copyright (C) 1997 Microsoft Corporation. All rights reserved
//-----------------------------------------------------------------------------
#ifndef D3DMATH_H
#define D3DMATH_H
#include <ddraw.h>
#include <d3d.h>
//-----------------------------------------------------------------------------
// Useful Math constants
//-----------------------------------------------------------------------------
const FLOAT g_PI = 3.14159265358979323846f; // Pi
const FLOAT g_2_PI = 6.28318530717958623200f; // 2 * Pi
const FLOAT g_PI_DIV_2 = 1.57079632679489655800f; // Pi / 2
const FLOAT g_PI_DIV_4 = 0.78539816339744827900f; // Pi / 4
const FLOAT g_INV_PI = 0.31830988618379069122f; // 1 / Pi
const FLOAT g_DEGTORAD = 0.01745329251994329547f; // Degrees to Radians
const FLOAT g_RADTODEG = 57.29577951308232286465f; // Radians to Degrees
const FLOAT g_HUGE = 1.0e+38f; // Huge number for FLOAT
const FLOAT g_EPSILON = 1.0e-5f; // Tolerance for FLOATs
//-----------------------------------------------------------------------------
// Fuzzy compares (within tolerance)
//-----------------------------------------------------------------------------
inline BOOL D3DMath_IsZero( FLOAT a, FLOAT fTol = g_EPSILON )
{ return ( a <= 0.0f ) ? ( a >= -fTol ) : ( a <= fTol ); }
//-----------------------------------------------------------------------------
// Matrix functions
//-----------------------------------------------------------------------------
VOID D3DMath_MatrixMultiply( D3DMATRIX& q, D3DMATRIX& a, D3DMATRIX& b );
HRESULT D3DMath_MatrixInvert( D3DMATRIX& q, D3DMATRIX& a );
//-----------------------------------------------------------------------------
// Vector functions
//-----------------------------------------------------------------------------
HRESULT D3DMath_VectorMatrixMultiply( D3DVECTOR& vDest, D3DVECTOR& vSrc,
D3DMATRIX& mat);
HRESULT D3DMath_VertexMatrixMultiply( D3DVERTEX& vDest, D3DVERTEX& vSrc,
D3DMATRIX& mat );
//-----------------------------------------------------------------------------
// Quaternion functions
//-----------------------------------------------------------------------------
VOID D3DMath_QuaternionFromRotation( FLOAT& x, FLOAT& y, FLOAT& z, FLOAT& w,
D3DVECTOR& v, FLOAT fTheta );
VOID D3DMath_RotationFromQuaternion( D3DVECTOR& v, FLOAT& fTheta,
FLOAT x, FLOAT y, FLOAT z, FLOAT w );
VOID D3DMath_QuaternionFromAngles( FLOAT& x, FLOAT& y, FLOAT& z, FLOAT& w,
FLOAT fYaw, FLOAT fPitch, FLOAT fRoll );
VOID D3DMath_MatrixFromQuaternion( D3DMATRIX& mat, FLOAT x, FLOAT y, FLOAT z,
FLOAT w );
VOID D3DMath_QuaternionFromMatrix( FLOAT &x, FLOAT &y, FLOAT &z, FLOAT &w,
D3DMATRIX& mat );
VOID D3DMath_QuaternionMultiply( FLOAT& Qx, FLOAT& Qy, FLOAT& Qz, FLOAT& Qw,
FLOAT Ax, FLOAT Ay, FLOAT Az, FLOAT Aw,
FLOAT Bx, FLOAT By, FLOAT Bz, FLOAT Bw );
VOID D3DMath_QuaternionSlerp( FLOAT& Qx, FLOAT& Qy, FLOAT& Qz, FLOAT& Qw,
FLOAT Ax, FLOAT Ay, FLOAT Az, FLOAT Aw,
FLOAT Bx, FLOAT By, FLOAT Bz, FLOAT Bw,
FLOAT fAlpha );
#endif // D3DMATH_H

View file

@ -1,788 +0,0 @@
//-----------------------------------------------------------------------------
// File: D3DTextr.cpp
//
// Desc: This file contains the member functions for the
// CD3DTextureEngine class. The class is responsible for loading and
// creating textures from files, as well as retrieving the
// corresponding ptrs and surfaces for the textures, given a
// texture's name.
//
//
// Copyright (c) 1996-1998 Microsoft Corporation. All rights reserved
//-----------------------------------------------------------------------------
#include <tchar.h>
#include <stdio.h>
#include "D3DTextr.h"
#include "D3DUtil.h"
//-----------------------------------------------------------------------------
// Name: TextureContainer
// Desc: Linked list tructure to hold info per texture
//-----------------------------------------------------------------------------
struct TextureContainer
{
HBITMAP hbmBitmap; // Bitmap containing texture image
LPDIRECTDRAWSURFACE4 pddsSurface; // Surface of the texture
LPDIRECT3DTEXTURE2 ptexTexture; // Direct3D texture for the texture
DWORD dwStage; // Texture stage (for multi-textures)
TCHAR strName[80]; // Filename of assoc'd bitmap
BOOL bHasAlpha;
DWORD dwFlags;
BYTE* pSurfaceBits[10];
DDSURFACEDESC2 ddsd;
TextureContainer *pPrev, *pNext; // Ptr to next texture in linked list
~TextureContainer();
};
//-----------------------------------------------------------------------------
// Macros, function prototypes and static variable
//-----------------------------------------------------------------------------
#define FOREACHTEXTURE(ptc) for( TextureContainer* ptc=g_ptcTextureList; \
NULL!=ptc; ptc=ptc->pNext )
inline BOOL FileExists( TCHAR* n )
{ FILE* fp=_tfopen(n,TEXT("rb")); return fp?(0==fclose(fp)):FALSE; }
static TextureContainer* g_ptcTextureList = NULL; // Textures list
static TCHAR g_strTexturePath[512] = TEXT("MEDIA\\"); // Path for files
static TCHAR* g_strRegValueName = TEXT("DX6SDK Samples Path");
struct TEXTURESEARCHINFO
{
DWORD dwDesiredBPP; // Input for texture format search
BOOL bUseAlpha;
BOOL bUsePalette;
BOOL bUseFourCC;
BOOL bFoundGoodFormat;
DDPIXELFORMAT* pddpf; // Result of texture format search
};
//-----------------------------------------------------------------------------
// Name: TextureSearchCallback()
// Desc: Enumeration callback routine to find a best-matching texture format.
// The param data is the DDPIXELFORMAT of the best-so-far matching
// texture. Note: the desired BPP is passed in the dwSize field, and the
// default BPP is passed in the dwFlags field.
//-----------------------------------------------------------------------------
static HRESULT CALLBACK TextureSearchCallback( DDPIXELFORMAT* pddpf,
VOID* param )
{
if( NULL==pddpf || NULL==param )
return DDENUMRET_OK;
TEXTURESEARCHINFO* ptsi = (TEXTURESEARCHINFO*)param;
// Skip any funky modes
if( pddpf->dwFlags & (DDPF_LUMINANCE|DDPF_BUMPLUMINANCE|DDPF_BUMPDUDV) )
return DDENUMRET_OK;
// Check for palettized formats
if( ptsi->bUsePalette )
{
if( !( pddpf->dwFlags & DDPF_PALETTEINDEXED8 ) )
return DDENUMRET_OK;
// Accept the first 8-bit palettized format we get
memcpy( ptsi->pddpf, pddpf, sizeof(DDPIXELFORMAT) );
ptsi->bFoundGoodFormat = TRUE;
return DDENUMRET_CANCEL;
}
// Else, skip any paletized formats (all modes under 16bpp)
if( pddpf->dwRGBBitCount < 16 )
return DDENUMRET_OK;
// Check for FourCC formats
if( ptsi->bUseFourCC )
{
if( pddpf->dwFourCC == 0 )
return DDENUMRET_OK;
return DDENUMRET_CANCEL;
}
// Else, skip any FourCC formats
if( pddpf->dwFourCC != 0 )
return DDENUMRET_OK;
// Make sure current alpha format agrees with requested format type
if( (ptsi->bUseAlpha==TRUE) && !(pddpf->dwFlags&DDPF_ALPHAPIXELS) )
return DDENUMRET_OK;
if( (ptsi->bUseAlpha==FALSE) && (pddpf->dwFlags&DDPF_ALPHAPIXELS) )
return DDENUMRET_OK;
// Check if we found a good match
if( pddpf->dwRGBBitCount == ptsi->dwDesiredBPP )
{
memcpy( ptsi->pddpf, pddpf, sizeof(DDPIXELFORMAT) );
ptsi->bFoundGoodFormat = TRUE;
return DDENUMRET_CANCEL;
}
return DDENUMRET_OK;
}
//-----------------------------------------------------------------------------
// Name: ~TextureContainer()
// Desc: Destructs the contents of the texture container
//-----------------------------------------------------------------------------
TextureContainer::~TextureContainer()
{
SAFE_DELETE( pNext );
SAFE_RELEASE( ptexTexture );
SAFE_RELEASE( pddsSurface );
DeleteObject( hbmBitmap );
}
//-----------------------------------------------------------------------------
// Name: CD3DStaticTextureEngine
// Desc: Class used to automatically construct and destruct the static
// texture engine class.
//-----------------------------------------------------------------------------
class CD3DTextureEngine
{
public:
CD3DTextureEngine();
~CD3DTextureEngine();
} g_StaticTextureEngine;
//-----------------------------------------------------------------------------
// Name: CD3DTextureEngine()
// Desc: Constructs the texture engine. Creates a DDraw object
//-----------------------------------------------------------------------------
CD3DTextureEngine::CD3DTextureEngine()
{
}
//-----------------------------------------------------------------------------
// Name: ~CD3DTextureEngine()
// Desc: Deletes the internal list of textures
//-----------------------------------------------------------------------------
CD3DTextureEngine::~CD3DTextureEngine()
{
// Delete the list of textures
SAFE_DELETE( g_ptcTextureList );
}
//-----------------------------------------------------------------------------
// Name: FindTexture()
// Desc: Searches the internal list of textures for a texture specified by
// its name. Returns the structure associated with that texture.
//-----------------------------------------------------------------------------
static TextureContainer* FindTexture( TCHAR* strTextureName )
{
FOREACHTEXTURE( ptcTexture )
{
if( !lstrcmpi( strTextureName, ptcTexture->strName ) )
return ptcTexture;
}
return NULL;
}
//-----------------------------------------------------------------------------
// Name: FindTextureFile()
// Desc: Looks for the specified file in the current directory, in the path
// specified in the environment variables, or in the path specified in
// the registry. After finding it, the function returns the full path.
//-----------------------------------------------------------------------------
static HRESULT FindTextureFile( TCHAR* strFilename, TCHAR* strTexturePath,
TCHAR* strFullPath )
{
// First, check the current directory
_tcscpy( strFullPath, strFilename );
if( FileExists( strFullPath ) )
return DD_OK;
// Next, check to see if an environment variable specifies the path
TCHAR* strPath = _tgetenv( TEXT("D3DPATH") );
if( NULL != strPath )
{
_stprintf( strFullPath, TEXT("%s\\%s"), strPath, strFilename );
if( FileExists( strFullPath ) )
return DD_OK;
}
// Finally, check the system registry for a path
HKEY key;
LONG result = RegOpenKeyEx( HKEY_LOCAL_MACHINE,
TEXT("Software\\Microsoft\\DirectX"),
0, KEY_READ, &key );
if( ERROR_SUCCESS == result )
{
TCHAR strPath[512];
DWORD type, size = 512;
result = RegQueryValueEx( key, g_strRegValueName, NULL, &type,
(BYTE*)strPath, &size );
RegCloseKey( key );
if( ERROR_SUCCESS == result )
{
_stprintf( strFullPath, TEXT("%s\\D3DIM\\Media\\%s"), strPath,
strFilename );
if( FileExists( strFullPath ) )
return DD_OK;
_stprintf( strFullPath, TEXT("%s\\%s%s"), strPath,
strTexturePath, strFilename );
if( FileExists( strFullPath ) )
return DD_OK;
}
}
return DDERR_NOTFOUND;
}
//-----------------------------------------------------------------------------
// Name: LoadTextureImage()
// Desc: Loads a texture map file into a BITMAP surface.
//-----------------------------------------------------------------------------
static HRESULT LoadTextureImage( TextureContainer* ptcTexture )
{
TCHAR* strFilename = ptcTexture->strName;
TCHAR* strExtension;
TCHAR strPathname[256];
// Get the filename extension
if( NULL == ( strExtension = _tcsrchr( strFilename, TEXT('.') ) ) )
return DDERR_UNSUPPORTED;
// Check the executable's resource. If it's there, we're done!
if( NULL != ( ptcTexture->hbmBitmap = (HBITMAP)LoadImage(
GetModuleHandle(NULL),
strFilename, IMAGE_BITMAP,
0, 0, LR_CREATEDIBSECTION) ) )
return S_OK;
// Check the current path and system registry path for the file
if( FAILED( FindTextureFile( strFilename, g_strTexturePath, strPathname ) ) )
return DDERR_NOTFOUND;
if( !lstrcmpi( strExtension, ".bmp" ) )
{
// Try to load the bitmap as a resource.
ptcTexture->hbmBitmap = (HBITMAP)LoadImage( GetModuleHandle(NULL),
strPathname, IMAGE_BITMAP, 0, 0,
LR_CREATEDIBSECTION );
// If the bitmap wasn't a resource, try it as a file.
if( NULL == ptcTexture->hbmBitmap )
ptcTexture->hbmBitmap = (HBITMAP)LoadImage( NULL, strPathname,
IMAGE_BITMAP, 0, 0,
LR_LOADFROMFILE|LR_CREATEDIBSECTION );
return (ptcTexture->hbmBitmap) ? DD_OK : DDERR_NOTFOUND;
}
// Can check for other file formats here
return DDERR_UNSUPPORTED;
}
//-----------------------------------------------------------------------------
// Name: CopyBitmapToSurface()
// Desc: Copies the image of a bitmap into a surface
//-----------------------------------------------------------------------------
static HRESULT CopyBitmapToSurface( LPDIRECTDRAWSURFACE4 pddsTarget,
HBITMAP hbmBitmap, DWORD dwFlags )
{
// Get a DDraw object to create a temporary surface
LPDIRECTDRAW4 pDD;
pddsTarget->GetDDInterface( (VOID**)&pDD );
pDD->Release();
// Get the bitmap structure (to extract width, height, and bpp)
BITMAP bm;
GetObject( hbmBitmap, sizeof(BITMAP), &bm );
// Setup the new surface desc
DDSURFACEDESC2 ddsd;
D3DUtil_InitSurfaceDesc( ddsd );
pddsTarget->GetSurfaceDesc( &ddsd );
ddsd.dwFlags = DDSD_CAPS|DDSD_HEIGHT|DDSD_WIDTH|DDSD_PIXELFORMAT|
DDSD_TEXTURESTAGE;
ddsd.ddsCaps.dwCaps = DDSCAPS_TEXTURE|DDSCAPS_SYSTEMMEMORY;
ddsd.ddsCaps.dwCaps2 = 0L;
ddsd.dwWidth = bm.bmWidth;
ddsd.dwHeight = bm.bmHeight;
// Create a new surface for the texture
LPDIRECTDRAWSURFACE4 pddsTempSurface;
HRESULT hr;
if( FAILED( hr = pDD->CreateSurface( &ddsd, &pddsTempSurface, NULL ) ) )
return NULL;
// Get a DC for the bitmap
HDC hdcBitmap = CreateCompatibleDC( NULL );
if( NULL == hdcBitmap )
{
pddsTempSurface->Release();
return NULL;
}
SelectObject( hdcBitmap, hbmBitmap );
// Handle palettized textures. Need to attach a palette
if( ddsd.ddpfPixelFormat.dwRGBBitCount == 8 )
{
// Create the color table and parse in the palette
DWORD pe[256];
WORD wNumColors = GetDIBColorTable( hdcBitmap, 0, 256,
(RGBQUAD*)pe );
for( WORD i=0; i<wNumColors; i++ )
{
pe[i] = 0xff000000 + RGB( GetBValue(pe[i]), GetGValue(pe[i]),
GetRValue(pe[i]) );
// Set alpha for transparent pixels
if( dwFlags & D3DTEXTR_TRANSPARENTBLACK )
{
if( (pe[i]&0x00ffffff) == 0x00000000 )
pe[i] &= 0x00ffffff;
}
else if( dwFlags & D3DTEXTR_TRANSPARENTWHITE )
{
if( (pe[i]&0x00ffffff) == 0x00ffffff )
pe[i] &= 0x00ffffff;
}
}
// Create & attach a palette with the bitmap's colors
LPDIRECTDRAWPALETTE pPalette;
if( dwFlags & (D3DTEXTR_TRANSPARENTWHITE|D3DTEXTR_TRANSPARENTBLACK) )
pDD->CreatePalette( DDPCAPS_8BIT|DDPCAPS_ALPHA, (PALETTEENTRY*)pe, &pPalette, NULL );
else
pDD->CreatePalette( DDPCAPS_8BIT, (PALETTEENTRY*)pe, &pPalette, NULL );
pddsTempSurface->SetPalette( pPalette );
pddsTarget->SetPalette( pPalette );
SAFE_RELEASE( pPalette );
}
// Copy the bitmap image to the surface.
HDC hdcSurface;
if( SUCCEEDED( pddsTempSurface->GetDC( &hdcSurface ) ) )
{
BitBlt( hdcSurface, 0, 0, bm.bmWidth, bm.bmHeight, hdcBitmap, 0, 0,
SRCCOPY );
pddsTempSurface->ReleaseDC( hdcSurface );
}
DeleteDC( hdcBitmap );
// Copy the temp surface to the real texture surface
pddsTarget->Blt( NULL, pddsTempSurface, NULL, DDBLT_WAIT, NULL );
if( ddsd.ddpfPixelFormat.dwRGBBitCount == 8 )
{
LPDIRECTDRAWPALETTE pPalette;
DWORD pe[256];
pddsTempSurface->GetPalette( &pPalette );
pPalette->GetEntries( 0, 0, 256, (PALETTEENTRY*)&pe );
pPalette->Release();
pddsTarget->GetPalette( &pPalette );
pPalette->GetEntries( 0, 0, 256, (PALETTEENTRY*)&pe );
pPalette->Release();
}
pddsTempSurface->Release();
// For textures with real alpha (not palettized), set transparent bits
if( ddsd.ddpfPixelFormat.dwRGBAlphaBitMask )
{
if( dwFlags & (D3DTEXTR_TRANSPARENTWHITE|D3DTEXTR_TRANSPARENTBLACK) )
{
// Lock the texture surface
DDSURFACEDESC2 ddsd;
D3DUtil_InitSurfaceDesc( ddsd );
while( pddsTarget->Lock( NULL, &ddsd, 0, NULL ) ==
DDERR_WASSTILLDRAWING );
DWORD dwAlphaMask = ddsd.ddpfPixelFormat.dwRGBAlphaBitMask;
DWORD dwRGBMask = ( ddsd.ddpfPixelFormat.dwRBitMask |
ddsd.ddpfPixelFormat.dwGBitMask |
ddsd.ddpfPixelFormat.dwBBitMask );
DWORD dwColorkey = 0x00000000; // Colorkey on black
if( dwFlags & D3DTEXTR_TRANSPARENTWHITE )
dwColorkey = dwRGBMask; // Colorkey on white
// Add an opaque alpha value to each non-colorkeyed pixel
for( DWORD y=0; y<ddsd.dwHeight; y++ )
{
WORD* p16 = (WORD*)((BYTE*)ddsd.lpSurface + y*ddsd.lPitch);
DWORD* p32 = (DWORD*)((BYTE*)ddsd.lpSurface + y*ddsd.lPitch);
for( DWORD x=0; x<ddsd.dwWidth; x++ )
{
if( ddsd.ddpfPixelFormat.dwRGBBitCount == 16 )
{
if( ( *p16 &= dwRGBMask ) != dwColorkey )
*p16 |= dwAlphaMask;
p16++;
}
if( ddsd.ddpfPixelFormat.dwRGBBitCount == 32 )
{
if( ( *p32 &= dwRGBMask ) != dwColorkey )
*p32 |= dwAlphaMask;
p32++;
}
}
}
pddsTarget->Unlock( NULL );
}
}
return S_OK;;
}
//-----------------------------------------------------------------------------
// Name: D3DTextr_GetSurface()
// Desc: Returns a pointer to a d3dSurface from the name of the texture
//-----------------------------------------------------------------------------
LPDIRECTDRAWSURFACE4 D3DTextr_GetSurface( TCHAR* strName )
{
TextureContainer* ptcTexture = FindTexture( strName );
return ptcTexture ? ptcTexture->pddsSurface : NULL;
}
//-----------------------------------------------------------------------------
// Name: D3DTextr_GetTexture()
// Desc: Returns a pointer to a d3dTexture from the name of the texture
//-----------------------------------------------------------------------------
LPDIRECT3DTEXTURE2 D3DTextr_GetTexture( TCHAR* strName )
{
TextureContainer* ptcTexture = FindTexture( strName );
return ptcTexture ? ptcTexture->ptexTexture: NULL;
}
//-----------------------------------------------------------------------------
// Name: D3DTextr_SetTexturePath()
// Desc: Enumeration callback routine to find a best-matching texture format.
//-----------------------------------------------------------------------------
VOID D3DTextr_SetTexturePath( TCHAR* strTexturePath )
{
if( NULL==strTexturePath )
strTexturePath = TEXT("");
_tcscpy( g_strTexturePath, strTexturePath );
}
//-----------------------------------------------------------------------------
// Name: D3DTextr_CreateTexture()
// Desc: Is passed a filename and creates a local Bitmap from that file.
// The texture can not be used until it is restored, however.
//-----------------------------------------------------------------------------
HRESULT D3DTextr_CreateTexture( TCHAR* strName, DWORD dwStage, DWORD dwFlags )
{
// Check first to see if the texture is already loaded
if( NULL != FindTexture( strName ) )
return S_OK;
// Allocate and add the texture to the linked list of textures;
TextureContainer* ptcTexture = new TextureContainer();
if( NULL == ptcTexture )
return E_OUTOFMEMORY;
ZeroMemory( ptcTexture, sizeof(TextureContainer) );
lstrcpy( ptcTexture->strName, strName );
ptcTexture->dwStage = dwStage;
ptcTexture->dwFlags = dwFlags;
// Create a bitmap and load the texture file into it,
if( FAILED( LoadTextureImage( ptcTexture ) ) )
{
delete ptcTexture;
return E_FAIL;
}
// Add the texture to the global linked list
if( g_ptcTextureList )
g_ptcTextureList->pPrev = ptcTexture;
ptcTexture->pNext = g_ptcTextureList;
g_ptcTextureList = ptcTexture;
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: RestoreFromBitmap()
// Desc: Invalidates the current texture objects and rebuilds new ones
// using the new device.
//-----------------------------------------------------------------------------
static HRESULT RestoreFromBitmap( TextureContainer* ptcTexture,
LPDIRECT3DDEVICE3 pd3dDevice )
{
// Get the DirectDraw interface for creating surfaces
LPDIRECTDRAW4 pDD;
if( NULL == ( pDD = D3DUtil_GetDirectDrawFromDevice( pd3dDevice ) ) )
return E_FAIL;
pDD->Release();
// Get the device caps
D3DDEVICEDESC ddHwDesc, ddSwDesc;
DWORD dwDeviceCaps;
ddHwDesc.dwSize = sizeof(D3DDEVICEDESC);
ddSwDesc.dwSize = sizeof(D3DDEVICEDESC);
if( FAILED( pd3dDevice->GetCaps( &ddHwDesc, &ddSwDesc ) ) )
return E_FAIL;
if( ddHwDesc.dwFlags ) dwDeviceCaps = ddHwDesc.dpcTriCaps.dwTextureCaps;
else dwDeviceCaps = ddSwDesc.dpcTriCaps.dwTextureCaps;
// Get the bitmap structure (to extract width, height, and bpp)
BITMAP bm;
HBITMAP hbmBitmap = ptcTexture->hbmBitmap;
GetObject( hbmBitmap, sizeof(BITMAP), &bm );
DWORD dwWidth = (DWORD)bm.bmWidth;
DWORD dwHeight = (DWORD)bm.bmHeight;
// Setup the new surface desc
DDSURFACEDESC2 ddsd;
D3DUtil_InitSurfaceDesc( ddsd );
ddsd.dwFlags = DDSD_CAPS|DDSD_HEIGHT|DDSD_WIDTH|
DDSD_PIXELFORMAT|DDSD_TEXTURESTAGE;
ddsd.ddsCaps.dwCaps = DDSCAPS_TEXTURE;
ddsd.ddsCaps.dwCaps2 = DDSCAPS2_TEXTUREMANAGE;
ddsd.dwTextureStage = ptcTexture->dwStage;
ddsd.dwWidth = dwWidth;
ddsd.dwHeight = dwHeight;
// Adjust width and height, if the driver requires it
if( dwDeviceCaps & D3DPTEXTURECAPS_POW2 )
{
for( ddsd.dwWidth=1; dwWidth>ddsd.dwWidth; ddsd.dwWidth<<=1 );
for( ddsd.dwHeight=1; dwHeight>ddsd.dwHeight; ddsd.dwHeight<<=1 );
}
if( dwDeviceCaps & D3DPTEXTURECAPS_SQUAREONLY )
{
if( ddsd.dwWidth > ddsd.dwHeight ) ddsd.dwHeight = ddsd.dwWidth;
else ddsd.dwWidth = ddsd.dwHeight;
}
BOOL bUsePalette = ( bm.bmBitsPixel <= 8 );
BOOL bUseAlpha = FALSE;
if( ptcTexture->bHasAlpha )
bUseAlpha = TRUE;
if( ptcTexture->dwFlags & (D3DTEXTR_TRANSPARENTWHITE|D3DTEXTR_TRANSPARENTBLACK) )
{
if( bUsePalette )
{
if( dwDeviceCaps & D3DPTEXTURECAPS_ALPHAPALETTE )
{
bUseAlpha = TRUE;
bUsePalette = TRUE;
}
else
{
bUseAlpha = TRUE;
bUsePalette = FALSE;
}
}
}
// Setup the structure to be used for texture enumration.
TEXTURESEARCHINFO tsi;
tsi.pddpf = &ddsd.ddpfPixelFormat;
tsi.bUseAlpha = bUseAlpha;
tsi.bUsePalette = bUsePalette;
tsi.bUseFourCC = ( ddsd.ddpfPixelFormat.dwFlags & DDPF_FOURCC );
tsi.dwDesiredBPP = 16;
tsi.bFoundGoodFormat = FALSE;
if( ptcTexture->dwFlags & D3DTEXTR_32BITSPERPIXEL )
tsi.dwDesiredBPP = 32;
// Enumerate the texture formats, and find the closest device-supported
// texture pixel format
pd3dDevice->EnumTextureFormats( TextureSearchCallback, &tsi );
// If a palettized format was requested, but not found, default to a
// 16-bit texture format
if( FALSE == tsi.bFoundGoodFormat && bUsePalette )
{
tsi.bUsePalette = FALSE;
tsi.dwDesiredBPP = 16;
pd3dDevice->EnumTextureFormats( TextureSearchCallback, &tsi );
if( FALSE == tsi.bFoundGoodFormat )
return E_FAIL;
}
// Create a new surface for the texture
HRESULT hr;
if( FAILED( hr = pDD->CreateSurface( &ddsd, &ptcTexture->pddsSurface, NULL ) ) )
return E_FAIL;
// Create the texture
if( FAILED( ptcTexture->pddsSurface->QueryInterface( IID_IDirect3DTexture2,
(VOID**)&ptcTexture->ptexTexture ) ) )
return E_FAIL;
// Copy the bitmap to the texture surface
return CopyBitmapToSurface( ptcTexture->pddsSurface, hbmBitmap,
ptcTexture->dwFlags );
}
//-----------------------------------------------------------------------------
// Name: D3DTextr_Restore()
// Desc: Invalidates the current texture objects and rebuilds new ones
// using the new device.
//-----------------------------------------------------------------------------
HRESULT D3DTextr_Restore( TCHAR* strName, LPDIRECT3DDEVICE3 pd3dDevice )
{
// Check params
if( NULL == pd3dDevice )
return DDERR_INVALIDPARAMS;
TextureContainer* ptcTexture = FindTexture( strName );
if( NULL == ptcTexture )
return DDERR_NOTFOUND;
// Release any previously created objects
SAFE_RELEASE( ptcTexture->ptexTexture );
SAFE_RELEASE( ptcTexture->pddsSurface );
// Restore the texture surface from the bitmap image. At this point, code
// can be added to handle other texture formats, such as those created from
// .dds files, .jpg files, or whatever else.
return RestoreFromBitmap( ptcTexture, pd3dDevice );
}
//-----------------------------------------------------------------------------
// Name: D3DTextr_RestoreAllTextures()
// Desc: This function is called when a mode is changed. It updates all
// texture objects to be valid with the new device.
//-----------------------------------------------------------------------------
HRESULT D3DTextr_RestoreAllTextures( LPDIRECT3DDEVICE3 pd3dDevice )
{
FOREACHTEXTURE( ptcTexture )
{
D3DTextr_Restore( ptcTexture->strName, pd3dDevice );
}
return DD_OK;
}
//-----------------------------------------------------------------------------
// Name: D3DTextr_Invalidate()
// Desc: Used to bump a texture out of (video) memory, this function
// actually destroys the d3dtexture and ddsurface of the texture
//-----------------------------------------------------------------------------
HRESULT D3DTextr_Invalidate( TCHAR* strName )
{
TextureContainer* ptcTexture = FindTexture( strName );
if( NULL == ptcTexture )
return DDERR_NOTFOUND;
SAFE_RELEASE( ptcTexture->ptexTexture );
SAFE_RELEASE( ptcTexture->pddsSurface );
return DD_OK;
}
//-----------------------------------------------------------------------------
// Name: D3DTextr_InvalidateAllTextures()
// Desc: This function is called when a mode is changed. It invalidates
// all texture objects so their device can be safely released.
//-----------------------------------------------------------------------------
HRESULT D3DTextr_InvalidateAllTextures()
{
FOREACHTEXTURE( ptcTexture )
{
SAFE_RELEASE( ptcTexture->ptexTexture );
SAFE_RELEASE( ptcTexture->pddsSurface );
}
return DD_OK;
}
//-----------------------------------------------------------------------------
// Name: D3DTextr_DestroyTexture()
// Desc: Frees the resources for the specified texture container
//-----------------------------------------------------------------------------
HRESULT D3DTextr_DestroyTexture( TCHAR* strName )
{
TextureContainer* ptcTexture = FindTexture( strName );
if( NULL == ptcTexture )
return DDERR_NOTFOUND;
// Remove the texture container from the global list
if( ptcTexture->pPrev )
ptcTexture->pPrev->pNext = ptcTexture->pNext;
else
g_ptcTextureList = ptcTexture->pNext;
ptcTexture->pNext = NULL;
SAFE_DELETE( ptcTexture );
return DD_OK;
}

View file

@ -1,62 +0,0 @@
//-----------------------------------------------------------------------------
// File: D3DTextr.h
//
// Desc: Functions to manage textures, including creating (loading from a
// file), restoring lost surfaces, invalidating, and destroying.
//
// Note: the implementation of these fucntions maintain an internal list
// of loaded textures. After creation, individual textures are referenced
// via their ASCII names.
//
//
// Copyright (C) 1997 Microsoft Corporation. All rights reserved
//-----------------------------------------------------------------------------
#ifndef D3DTEXTR_H
#define D3DTEXTR_H
#include <ddraw.h>
#include <d3d.h>
//-----------------------------------------------------------------------------
// Access functions for loaded textures. Note: these functions search
// an internal list of the textures, and use the texture associated with the
// ASCII name.
//-----------------------------------------------------------------------------
LPDIRECTDRAWSURFACE4 D3DTextr_GetSurface( TCHAR* strName );
LPDIRECT3DTEXTURE2 D3DTextr_GetTexture( TCHAR* strName );
//-----------------------------------------------------------------------------
// Texture invalidation and restoration functions
//-----------------------------------------------------------------------------
HRESULT D3DTextr_Invalidate( TCHAR* strName );
HRESULT D3DTextr_Restore( TCHAR* strName, LPDIRECT3DDEVICE3 pd3dDevice );
HRESULT D3DTextr_InvalidateAllTextures();
HRESULT D3DTextr_RestoreAllTextures( LPDIRECT3DDEVICE3 pd3dDevice );
//-----------------------------------------------------------------------------
// Texture creation and deletion functions
//-----------------------------------------------------------------------------
#define D3DTEXTR_TRANSPARENTWHITE 0x00000001
#define D3DTEXTR_TRANSPARENTBLACK 0x00000002
#define D3DTEXTR_32BITSPERPIXEL 0x00000004
HRESULT D3DTextr_CreateTexture( TCHAR* strName, DWORD dwStage=0L,
DWORD dwFlags=0L );
HRESULT D3DTextr_DestroyTexture( TCHAR* strName );
VOID D3DTextr_SetTexturePath( TCHAR* strTexturePath );
#endif // D3DTEXTR_H

View file

@ -1,390 +0,0 @@
//-----------------------------------------------------------------------------
// File: D3DUtil.cpp
//
// Desc: Shortcut macros and functions for using DX objects
//
//
// Copyright (c) 1997-1998 Microsoft Corporation. All rights reserved
//-----------------------------------------------------------------------------
#define D3D_OVERLOADS
#include <math.h>
#include <stdio.h>
#include "D3DUtil.h"
//-----------------------------------------------------------------------------
// Name: D3DUtil_InitDeviceDesc()
// Desc: Helper function called to initialize a D3DDEVICEDESC structure,
//-----------------------------------------------------------------------------
VOID D3DUtil_InitDeviceDesc( D3DDEVICEDESC& ddDevDesc )
{
ZeroMemory( &ddDevDesc, sizeof(D3DDEVICEDESC) );
ddDevDesc.dwSize = sizeof(D3DDEVICEDESC);
ddDevDesc.dtcTransformCaps.dwSize = sizeof(D3DTRANSFORMCAPS);
ddDevDesc.dlcLightingCaps.dwSize = sizeof(D3DLIGHTINGCAPS);
ddDevDesc.dpcLineCaps.dwSize = sizeof(D3DPRIMCAPS);
ddDevDesc.dpcTriCaps.dwSize = sizeof(D3DPRIMCAPS);
}
//-----------------------------------------------------------------------------
// Name: D3DUtil_InitSurfaceDesc()
// Desc: Helper function called to build a DDSURFACEDESC2 structure,
// typically before calling CreateSurface() or GetSurfaceDesc()
//-----------------------------------------------------------------------------
VOID D3DUtil_InitSurfaceDesc( DDSURFACEDESC2& ddsd, DWORD dwFlags,
DWORD dwCaps )
{
ZeroMemory( &ddsd, sizeof(DDSURFACEDESC2) );
ddsd.dwSize = sizeof(DDSURFACEDESC2);
ddsd.dwFlags = dwFlags;
ddsd.ddsCaps.dwCaps = dwCaps;
ddsd.ddpfPixelFormat.dwSize = sizeof(DDPIXELFORMAT);
}
//-----------------------------------------------------------------------------
// Name: D3DUtil_InitViewport()
// Desc: Helper function called to build a D3DVIEWPORT3 structure
//-----------------------------------------------------------------------------
VOID D3DUtil_InitViewport( D3DVIEWPORT2& vp, DWORD dwWidth, DWORD dwHeight )
{
ZeroMemory( &vp, sizeof(D3DVIEWPORT2) );
vp.dwSize = sizeof(D3DVIEWPORT2);
vp.dwWidth = dwWidth;
vp.dwHeight = dwHeight;
vp.dvMaxZ = 1.0f;
vp.dvClipX = -1.0f;
vp.dvClipWidth = 2.0f;
vp.dvClipY = 1.0f;
vp.dvClipHeight = 2.0f;
}
//-----------------------------------------------------------------------------
// Name: D3DUtil_InitMaterial()
// Desc: Helper function called to build a D3DMATERIAL structure
//-----------------------------------------------------------------------------
VOID D3DUtil_InitMaterial( D3DMATERIAL& mtrl, FLOAT r, FLOAT g, FLOAT b )
{
ZeroMemory( &mtrl, sizeof(D3DMATERIAL) );
mtrl.dwSize = sizeof(D3DMATERIAL);
mtrl.dcvDiffuse.r = mtrl.dcvAmbient.r = r;
mtrl.dcvDiffuse.g = mtrl.dcvAmbient.g = g;
mtrl.dcvDiffuse.b = mtrl.dcvAmbient.b = b;
mtrl.dwRampSize = 16L; // A default ramp size
}
//-----------------------------------------------------------------------------
// Name: D3DUtil_InitLight()
// Desc: Initializes a D3DLIGHT structure
//-----------------------------------------------------------------------------
VOID D3DUtil_InitLight( D3DLIGHT& light, D3DLIGHTTYPE ltType,
FLOAT x, FLOAT y, FLOAT z )
{
ZeroMemory( &light, sizeof(D3DLIGHT) );
light.dwSize = sizeof(D3DLIGHT);
light.dltType = ltType;
light.dcvColor.r = 1.0f;
light.dcvColor.g = 1.0f;
light.dcvColor.b = 1.0f;
light.dvPosition.x = light.dvDirection.x = x;
light.dvPosition.y = light.dvDirection.y = y;
light.dvPosition.z = light.dvDirection.z = z;
}
//-----------------------------------------------------------------------------
// Name: D3DUtil_GetDirectDrawFromDevice()
// Desc: Get the DDraw interface from a D3DDevice.
//-----------------------------------------------------------------------------
LPDIRECTDRAW4 D3DUtil_GetDirectDrawFromDevice( LPDIRECT3DDEVICE3 pd3dDevice )
{
LPDIRECTDRAW4 pDD = NULL;
LPDIRECTDRAWSURFACE4 pddsRender;
if( pd3dDevice )
{
// Get the current render target
if( SUCCEEDED( pd3dDevice->GetRenderTarget( &pddsRender ) ) )
{
// Get the DDraw4 interface from the render target
pddsRender->GetDDInterface( (VOID**)&pDD );
pddsRender->Release();
}
}
return pDD;
}
//-----------------------------------------------------------------------------
// Name: D3DUtil_GetDeviceMemoryType()
// Desc: Retreives the default memory type used for the device.
//-----------------------------------------------------------------------------
DWORD D3DUtil_GetDeviceMemoryType( LPDIRECT3DDEVICE3 pd3dDevice )
{
D3DDEVICEDESC ddHwDesc, ddSwDesc;
ddHwDesc.dwSize = sizeof(D3DDEVICEDESC);
ddSwDesc.dwSize = sizeof(D3DDEVICEDESC);
if( FAILED( pd3dDevice->GetCaps( &ddHwDesc, &ddSwDesc ) ) )
return 0L;
if( ddHwDesc.dwFlags )
return DDSCAPS_VIDEOMEMORY;
return DDSCAPS_SYSTEMMEMORY;
}
//-----------------------------------------------------------------------------
// Name: D3DUtil_SetViewMatrix()
// Desc: Given an eye point, a lookat point, and an up vector, this
// function builds a 4x4 view matrix.
//-----------------------------------------------------------------------------
HRESULT D3DUtil_SetViewMatrix( D3DMATRIX& mat, D3DVECTOR& vFrom,
D3DVECTOR& vAt, D3DVECTOR& vWorldUp )
{
// Get the z basis vector, which points straight ahead. This is the
// difference from the eyepoint to the lookat point.
D3DVECTOR vView = vAt - vFrom;
FLOAT fLength = Magnitude( vView );
if( fLength < 1e-6f )
return E_INVALIDARG;
// Normalize the z basis vector
vView /= fLength;
// Get the dot product, and calculate the projection of the z basis
// vector onto the up vector. The projection is the y basis vector.
FLOAT fDotProduct = DotProduct( vWorldUp, vView );
D3DVECTOR vUp = vWorldUp - fDotProduct * vView;
// If this vector has near-zero length because the input specified a
// bogus up vector, let's try a default up vector
if( 1e-6f > ( fLength = Magnitude( vUp ) ) )
{
vUp = D3DVECTOR( 0.0f, 1.0f, 0.0f ) - vView.y * vView;
// If we still have near-zero length, resort to a different axis.
if( 1e-6f > ( fLength = Magnitude( vUp ) ) )
{
vUp = D3DVECTOR( 0.0f, 0.0f, 1.0f ) - vView.z * vView;
if( 1e-6f > ( fLength = Magnitude( vUp ) ) )
return E_INVALIDARG;
}
}
// Normalize the y basis vector
vUp /= fLength;
// The x basis vector is found simply with the cross product of the y
// and z basis vectors
D3DVECTOR vRight = CrossProduct( vUp, vView );
// Start building the matrix. The first three rows contains the basis
// vectors used to rotate the view to point at the lookat point
D3DUtil_SetIdentityMatrix( mat );
mat._11 = vRight.x; mat._12 = vUp.x; mat._13 = vView.x;
mat._21 = vRight.y; mat._22 = vUp.y; mat._23 = vView.y;
mat._31 = vRight.z; mat._32 = vUp.z; mat._33 = vView.z;
// Do the translation values (rotations are still about the eyepoint)
mat._41 = - DotProduct( vFrom, vRight );
mat._42 = - DotProduct( vFrom, vUp );
mat._43 = - DotProduct( vFrom, vView );
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: D3DUtil_SetProjectionMatrix()
// Desc: Sets the passed in 4x4 matrix to a perpsective projection matrix built
// from the field-of-view (fov, in y), aspect ratio, near plane (D),
// and far plane (F). Note that the projection matrix is normalized for
// element [3][4] to be 1.0. This is performed so that W-based range fog
// will work correctly.
//-----------------------------------------------------------------------------
HRESULT D3DUtil_SetProjectionMatrix( D3DMATRIX& mat, FLOAT fFOV, FLOAT fAspect,
FLOAT fNearPlane, FLOAT fFarPlane )
{
if( fabs(fFarPlane-fNearPlane) < 0.01f )
return E_INVALIDARG;
if( fabs(sin(fFOV/2)) < 0.01f )
return E_INVALIDARG;
FLOAT w = fAspect * (FLOAT)( cos(fFOV/2)/sin(fFOV/2) );
FLOAT h = 1.0f * (FLOAT)( cos(fFOV/2)/sin(fFOV/2) );
FLOAT Q = fFarPlane / ( fFarPlane - fNearPlane );
ZeroMemory( &mat, sizeof(D3DMATRIX) );
mat._11 = w;
mat._22 = h;
mat._33 = Q;
mat._34 = 1.0f;
mat._43 = -Q*fNearPlane;
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: D3DUtil_SetRotateXMatrix()
// Desc: Create Rotation matrix about X axis
//-----------------------------------------------------------------------------
VOID D3DUtil_SetRotateXMatrix( D3DMATRIX& mat, FLOAT fRads )
{
D3DUtil_SetIdentityMatrix( mat );
mat._22 = (FLOAT)cos( fRads );
mat._23 = (FLOAT)sin( fRads );
mat._32 = -(FLOAT)sin( fRads );
mat._33 = (FLOAT)cos( fRads );
}
//-----------------------------------------------------------------------------
// Name: D3DUtil_SetRotateYMatrix()
// Desc: Create Rotation matrix about Y axis
//-----------------------------------------------------------------------------
VOID D3DUtil_SetRotateYMatrix( D3DMATRIX& mat, FLOAT fRads )
{
D3DUtil_SetIdentityMatrix( mat );
mat._11 = (FLOAT)cos( fRads );
mat._13 = -(FLOAT)sin( fRads );
mat._31 = (FLOAT)sin( fRads );
mat._33 = (FLOAT)cos( fRads );
}
//-----------------------------------------------------------------------------
// Name: D3DUtil_SetRotateZMatrix()
// Desc: Create Rotation matrix about Z axis
//-----------------------------------------------------------------------------
VOID D3DUtil_SetRotateZMatrix( D3DMATRIX& mat, FLOAT fRads )
{
D3DUtil_SetIdentityMatrix( mat );
mat._11 = (FLOAT)cos( fRads );
mat._12 = (FLOAT)sin( fRads );
mat._21 = -(FLOAT)sin( fRads );
mat._22 = (FLOAT)cos( fRads );
}
//-----------------------------------------------------------------------------
// Name: D3DUtil_SetRotationMatrix
// Desc: Create a Rotation matrix about vector direction
//-----------------------------------------------------------------------------
VOID D3DUtil_SetRotationMatrix( D3DMATRIX& mat, D3DVECTOR& vDir, FLOAT fRads )
{
FLOAT fCos = (FLOAT)cos( fRads );
FLOAT fSin = (FLOAT)sin( fRads );
D3DVECTOR v = Normalize( vDir );
mat._11 = ( v.x * v.x ) * ( 1.0f - fCos ) + fCos;
mat._12 = ( v.x * v.y ) * ( 1.0f - fCos ) - (v.z * fSin);
mat._13 = ( v.x * v.z ) * ( 1.0f - fCos ) + (v.y * fSin);
mat._21 = ( v.y * v.x ) * ( 1.0f - fCos ) + (v.z * fSin);
mat._22 = ( v.y * v.y ) * ( 1.0f - fCos ) + fCos ;
mat._23 = ( v.y * v.z ) * ( 1.0f - fCos ) - (v.x * fSin);
mat._31 = ( v.z * v.x ) * ( 1.0f - fCos ) - (v.y * fSin);
mat._32 = ( v.z * v.y ) * ( 1.0f - fCos ) + (v.x * fSin);
mat._33 = ( v.z * v.z ) * ( 1.0f - fCos ) + fCos;
mat._14 = mat._24 = mat._34 = 0.0f;
mat._41 = mat._42 = mat._43 = 0.0f;
mat._44 = 1.0f;
}
//-----------------------------------------------------------------------------
// Name: D3DUtil_GetDisplayDepth()
// Desc: Returns the depth of the current display mode.
//-----------------------------------------------------------------------------
DWORD D3DUtil_GetDisplayDepth( LPDIRECTDRAW4 pDD4 )
{
// If the caller did not supply a DDraw object, just create a temp one.
if( NULL == pDD4 )
{
LPDIRECTDRAW pDD1;
if( FAILED( DirectDrawCreate( NULL, &pDD1, NULL ) ) )
return 0L;
HRESULT hr = pDD1->QueryInterface( IID_IDirectDraw4, (VOID**)&pDD4 );
pDD1->Release();
if( FAILED(hr) )
return 0L;
}
else
pDD4->AddRef();
// Get the display mode description
DDSURFACEDESC2 ddsd;
ZeroMemory( &ddsd, sizeof(DDSURFACEDESC2) );
ddsd.dwSize = sizeof(DDSURFACEDESC2);
pDD4->GetDisplayMode( &ddsd );
pDD4->Release();
// Return the display mode's depth
return ddsd.ddpfPixelFormat.dwRGBBitCount;
}
//-----------------------------------------------------------------------------
// Name: _DbgOut()
// Desc: Outputs a message to the debug stream
//-----------------------------------------------------------------------------
HRESULT _DbgOut( TCHAR* strFile, DWORD dwLine, HRESULT hr, TCHAR* strMsg )
{
TCHAR buffer[256];
sprintf( buffer, "%s(%ld): ", strFile, dwLine );
OutputDebugString( buffer );
OutputDebugString( strMsg );
if( hr )
{
sprintf( buffer, "(hr=%08lx)\n", hr );
OutputDebugString( buffer );
}
OutputDebugString( "\n" );
return hr;
}

View file

@ -1,110 +0,0 @@
//-----------------------------------------------------------------------------
// File: D3DUtil.h
//
// Desc: Helper functions and typing shortcuts for Direct3D programming.
//
//
// Copyright (C) 1997 Microsoft Corporation. All rights reserved
//-----------------------------------------------------------------------------
#ifndef D3DUTIL_H
#define D3DUTIL_H
#include <ddraw.h>
#include <d3d.h>
//-----------------------------------------------------------------------------
// Typing shortcuts for deleting and freeing objects.
//-----------------------------------------------------------------------------
#define SAFE_DELETE(p) { if(p) { delete (p); (p)=NULL; } }
#define SAFE_RELEASE(p) { if(p) { (p)->Release(); (p)=NULL; } }
//-----------------------------------------------------------------------------
// Short cut functions for creating and using DX structures
//-----------------------------------------------------------------------------
VOID D3DUtil_InitDeviceDesc( D3DDEVICEDESC& ddDevDesc );
VOID D3DUtil_InitSurfaceDesc( DDSURFACEDESC2& ddsd, DWORD dwFlags=0,
DWORD dwCaps=0 );
VOID D3DUtil_InitViewport( D3DVIEWPORT2& vdViewData, DWORD dwWidth=0,
DWORD dwHeight=0 );
VOID D3DUtil_InitMaterial( D3DMATERIAL& mdMtrlData, FLOAT r=0.0f, FLOAT g=0.0f,
FLOAT b=0.0f );
VOID D3DUtil_InitLight( D3DLIGHT& ldLightData, D3DLIGHTTYPE ltType,
FLOAT x=0.0f, FLOAT y=0.0f, FLOAT z=0.0f );
//-----------------------------------------------------------------------------
// Miscellaneous helper functions
//-----------------------------------------------------------------------------
LPDIRECTDRAW4 D3DUtil_GetDirectDrawFromDevice( LPDIRECT3DDEVICE3 pd3dDevice );
DWORD D3DUtil_GetDeviceMemoryType( LPDIRECT3DDEVICE3 pd3dDevice );
DWORD D3DUtil_GetDisplayDepth( LPDIRECTDRAW4 pDD4=NULL );
//-----------------------------------------------------------------------------
// D3D Matrix functions. For performance reasons, some functions are inline.
//-----------------------------------------------------------------------------
HRESULT D3DUtil_SetViewMatrix( D3DMATRIX& mat, D3DVECTOR& vFrom,
D3DVECTOR& vAt, D3DVECTOR& vUp );
HRESULT D3DUtil_SetProjectionMatrix( D3DMATRIX& mat, FLOAT fFOV = 1.570795f,
FLOAT fAspect = 1.0f,
FLOAT fNearPlane = 1.0f,
FLOAT fFarPlane = 1000.0f );
inline VOID D3DUtil_SetIdentityMatrix( D3DMATRIX& m )
{
m._12 = m._13 = m._14 = m._21 = m._23 = m._24 = 0.0f;
m._31 = m._32 = m._34 = m._41 = m._42 = m._43 = 0.0f;
m._11 = m._22 = m._33 = m._44 = 1.0f;
}
inline VOID D3DUtil_SetTranslateMatrix( D3DMATRIX& m, FLOAT tx, FLOAT ty,
FLOAT tz )
{ D3DUtil_SetIdentityMatrix( m ); m._41 = tx; m._42 = ty; m._43 = tz; }
inline VOID D3DUtil_SetTranslateMatrix( D3DMATRIX& m, D3DVECTOR& v )
{ D3DUtil_SetTranslateMatrix( m, v.x, v.y, v.z ); }
inline VOID D3DUtil_SetScaleMatrix( D3DMATRIX& m, FLOAT sx, FLOAT sy,
FLOAT sz )
{ D3DUtil_SetIdentityMatrix( m ); m._11 = sx; m._22 = sy; m._33 = sz; }
inline VOID SetScaleMatrix( D3DMATRIX& m, D3DVECTOR& v )
{ D3DUtil_SetScaleMatrix( m, v.x, v.y, v.z ); }
VOID D3DUtil_SetRotateXMatrix( D3DMATRIX& mat, FLOAT fRads );
VOID D3DUtil_SetRotateYMatrix( D3DMATRIX& mat, FLOAT fRads );
VOID D3DUtil_SetRotateZMatrix( D3DMATRIX& mat, FLOAT fRads );
VOID D3DUtil_SetRotationMatrix( D3DMATRIX& mat, D3DVECTOR& vDir,
FLOAT fRads );
//-----------------------------------------------------------------------------
// Debug printing support
//-----------------------------------------------------------------------------
HRESULT _DbgOut( TCHAR*, DWORD, HRESULT, TCHAR* );
#if defined(DEBUG) | defined(_DEBUG)
#define DEBUG_MSG(str) _DbgOut( __FILE__, (DWORD)__LINE__, 0, str )
#define DEBUG_ERR(hr,str) _DbgOut( __FILE__, (DWORD)__LINE__, hr, str )
#else
#define DEBUG_MSG(str) (0L)
#define DEBUG_ERR(hr,str) (hr)
#endif
#endif // D3DUTIL_H

View file

@ -1,314 +0,0 @@
//-----------------------------------------------------------------------------
// File: ddenum.cpp
//
// Desc: This sample demonstrates how to enumerate all of the devices and show
// the driver information about each.
//
//
// Copyright (c) 1998 Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
//-----------------------------------------------------------------------------
// Include files
//-----------------------------------------------------------------------------
#include <stdio.h>
#include <stdarg.h>
#include <windows.h>
#include <ddraw.h>
#include "resource.h"
//-----------------------------------------------------------------------------
// Local definitions
//-----------------------------------------------------------------------------
#define NAME "DDEnum"
#define TITLE "DirectDraw Enumeration Example"
//-----------------------------------------------------------------------------
// Default settings
//-----------------------------------------------------------------------------
#define MAX_DEVICES 16
//-----------------------------------------------------------------------------
// Global Variables
//-----------------------------------------------------------------------------
int g_iMaxDevices = 0;
struct{
DDDEVICEIDENTIFIER DeviceInfo;
DDDEVICEIDENTIFIER DeviceInfoHost;
} g_DeviceInfo[MAX_DEVICES];
//-----------------------------------------------------------------------------
// Name: InitFail()
// Desc: This function is called if an initialization function fails
//-----------------------------------------------------------------------------
void
InitFail(LPCTSTR szError, ...)
{
char szBuff[128];
va_list vl;
va_start(vl, szError);
vsprintf(szBuff, szError, vl);
MessageBox(NULL, szBuff, TITLE, MB_OK);
va_end(vl);
}
//-----------------------------------------------------------------------------
// Name: SetInfoDlgText()
// Desc: Update all of the text and buttons in the dialog
//-----------------------------------------------------------------------------
void
SetInfoDlgText(HWND hDlg, int iCurrent, DWORD dwHost)
{
char szBuff[128];
GUID *pGUID;
LPDDDEVICEIDENTIFIER pDI;
if (dwHost == DDGDI_GETHOSTIDENTIFIER)
CheckRadioButton( hDlg, IDC_RADIO_DEVICE, IDC_RADIO_HOST, IDC_RADIO_HOST );
else
CheckRadioButton( hDlg, IDC_RADIO_DEVICE, IDC_RADIO_DEVICE, IDC_RADIO_DEVICE );
pDI = &g_DeviceInfo[iCurrent].DeviceInfo;
if (dwHost == DDGDI_GETHOSTIDENTIFIER)
pDI = &g_DeviceInfo[iCurrent].DeviceInfoHost;
wsprintf(szBuff, "Device information for device %d of %d",iCurrent + 1,g_iMaxDevices);
SetDlgItemText( hDlg, IDC_RADIO_DEVICE, szBuff);
//Device ID stuff:
wsprintf(szBuff,"%08X",pDI->dwVendorId);
SetDlgItemText( hDlg, IDC_DWVENDORID, szBuff);
wsprintf(szBuff,"%08X",pDI->dwDeviceId);
SetDlgItemText( hDlg, IDC_DWDEVICEID, szBuff);
wsprintf(szBuff,"%08X",pDI->dwSubSysId);
SetDlgItemText( hDlg, IDC_DWSUBSYS, szBuff);
wsprintf(szBuff,"%08X",pDI->dwRevision);
SetDlgItemText( hDlg, IDC_DWREVISION, szBuff);
//Driver version:
wsprintf(szBuff,"%d.%02d.%02d.%04d",
HIWORD(pDI->liDriverVersion.u.HighPart),
LOWORD(pDI->liDriverVersion.u.HighPart),
HIWORD(pDI->liDriverVersion.u.LowPart),
LOWORD(pDI->liDriverVersion.u.LowPart) );
SetDlgItemText( hDlg, IDC_VERSION, szBuff);
//Device description and HAL filename
SetDlgItemText( hDlg, IDC_DESCRIPTION, pDI->szDescription);
SetDlgItemText( hDlg, IDC_FILENAME, pDI->szDriver);
//Unique driver/device identifier:
pGUID = &pDI->guidDeviceIdentifier;
wsprintf(szBuff, "%08X-%04X-%04X-%02X%02X%02X%02X%02X%02X%02X%02X",
pGUID->Data1, pGUID->Data2, pGUID->Data3,
pGUID->Data4[0], pGUID->Data4[1], pGUID->Data4[2], pGUID->Data4[3],
pGUID->Data4[4], pGUID->Data4[5], pGUID->Data4[6], pGUID->Data4[7]);
SetDlgItemText( hDlg, IDC_GUID, szBuff);
// Change the state and style of the Prev and Next buttons if needed
if (0 == iCurrent)
{
// The Prev button should be disabled
SetFocus(GetDlgItem(hDlg, IDOK));
SendDlgItemMessage( hDlg, IDC_PREV, BM_SETSTYLE, BS_PUSHBUTTON, TRUE);
SendMessage(hDlg, DM_SETDEFID, IDOK, 0);
EnableWindow(GetDlgItem(hDlg, IDC_PREV), FALSE);
}
else
if (IsWindowEnabled(GetDlgItem(hDlg, IDC_PREV)) == FALSE)
EnableWindow(GetDlgItem(hDlg, IDC_PREV), TRUE);
if (iCurrent >= (g_iMaxDevices - 1))
{
// The Next button should be disabled
SetFocus(GetDlgItem(hDlg, IDOK));
SendDlgItemMessage( hDlg, IDC_NEXT, BM_SETSTYLE, BS_PUSHBUTTON, TRUE);
SendMessage(hDlg, DM_SETDEFID, IDOK, 0);
EnableWindow(GetDlgItem(hDlg, IDC_NEXT), FALSE);
}
else
if (IsWindowEnabled(GetDlgItem(hDlg, IDC_NEXT)) == FALSE)
EnableWindow(GetDlgItem(hDlg, IDC_NEXT), TRUE);
}
//-----------------------------------------------------------------------------
// Name: InfoDlgProc()
// Desc: The dialog window proc
//-----------------------------------------------------------------------------
LRESULT CALLBACK
InfoDlgProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
// RECT rc;
static int iCurrent = 0;
static DWORD dwHost = 0;
switch (uMsg)
{
case WM_INITDIALOG:
// Setup the first devices text
SetInfoDlgText(hDlg, iCurrent, dwHost);
return TRUE;
case WM_COMMAND:
switch (HIWORD(wParam))
{
case BN_CLICKED:
switch (LOWORD(wParam))
{
case IDOK:
case IDCANCEL:
EndDialog(hDlg, TRUE);
return TRUE;
case IDC_PREV:
// Show the previous device
if (iCurrent)
iCurrent--;
SetInfoDlgText(hDlg, iCurrent, dwHost);
break;
case IDC_NEXT:
// Show the next device
if (iCurrent < g_iMaxDevices)
iCurrent++;
SetInfoDlgText(hDlg, iCurrent, dwHost);
break;
case IDC_RADIO_HOST:
case IDC_RADIO_DEVICE:
if (dwHost == DDGDI_GETHOSTIDENTIFIER )
dwHost = 0;
else
dwHost = DDGDI_GETHOSTIDENTIFIER;
SetInfoDlgText(hDlg, iCurrent, dwHost);
break;
}
break;
}
break;
}
return FALSE;
}
//-----------------------------------------------------------------------------
// Name: DDEnumCallbackEx()
// Desc: This callback gets the information for each device enumerated
//-----------------------------------------------------------------------------
BOOL WINAPI
DDEnumCallbackEx(GUID *pGUID, LPSTR pDescription, LPSTR pName,
LPVOID pContext, HMONITOR hm)
{
LPDIRECTDRAW pDD; // DD1 interface, used to get DD4 interface
LPDIRECTDRAW4 pDD4 = NULL; // DirectDraw4 interface
HRESULT hRet;
// Create the main DirectDraw object
hRet = DirectDrawCreate(pGUID, &pDD, NULL);
if (hRet != DD_OK)
{
InitFail("DirectDrawCreate FAILED");
return DDENUMRET_CANCEL;
}
// Fetch DirectDraw4 interface
hRet = pDD->QueryInterface(IID_IDirectDraw4, (LPVOID *)&pDD4);
if (hRet != DD_OK)
{
InitFail("QueryInterface FAILED");
return DDENUMRET_CANCEL;
}
// Get the device information and save it
hRet = pDD4->GetDeviceIdentifier(&g_DeviceInfo[g_iMaxDevices].DeviceInfo,0);
hRet = pDD4->GetDeviceIdentifier(&g_DeviceInfo[g_iMaxDevices].DeviceInfoHost,DDGDI_GETHOSTIDENTIFIER);
// Finished with the DirectDraw object, so release it
if (pDD4)
pDD4->Release();
// Bump to the next open slot or finish the callbacks if full
if (g_iMaxDevices < MAX_DEVICES)
g_iMaxDevices++;
else
return DDENUMRET_CANCEL;
return DDENUMRET_OK;
}
//-----------------------------------------------------------------------------
// Name: DDEnumCallback()
// Desc: Old style callback retained for backwards compatibility
//-----------------------------------------------------------------------------
BOOL WINAPI
DDEnumCallback(GUID *pGUID, LPSTR pDescription, LPSTR pName, LPVOID context)
{
return (DDEnumCallbackEx(pGUID, pDescription, pName, context, NULL));
}
//-----------------------------------------------------------------------------
// Name: WinMain()
// Desc: Entry point to the program. Initializes everything and calls
// DirectDrawEnumerateEx() to get all of the device info.
//-----------------------------------------------------------------------------
int PASCAL
WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpszCmdLine,
int nCmdShow)
{
LPDIRECTDRAWENUMERATEEX pDirectDrawEnumerateEx;
HINSTANCE hDDrawDLL;
// Do a GetModuleHandle and GetProcAddress in order to get the
// DirectDrawEnumerateEx function
hDDrawDLL = GetModuleHandle("DDRAW");
if (!hDDrawDLL)
{
InitFail("LoadLibrary() FAILED");
return -1;
}
pDirectDrawEnumerateEx = (LPDIRECTDRAWENUMERATEEX )GetProcAddress(hDDrawDLL,"DirectDrawEnumerateExA");
if (pDirectDrawEnumerateEx)
{
pDirectDrawEnumerateEx(DDEnumCallbackEx, NULL,
DDENUM_ATTACHEDSECONDARYDEVICES |
DDENUM_DETACHEDSECONDARYDEVICES |
DDENUM_NONDISPLAYDEVICES);
}
else
{
// Old DirectDraw, so do it the old way
DirectDrawEnumerate(DDEnumCallback, NULL);
}
if (0 == g_iMaxDevices)
{
InitFail("No devices to enumerate.");
return -1;
}
// Bring up the dialog to show all the devices
DialogBox(hInstance, MAKEINTRESOURCE(IDD_DRIVERINFO), GetDesktopWindow(), (DLGPROC) InfoDlgProc);
return 0;
}

View file

@ -1,21 +0,0 @@
/*==========================================================================
*
* Copyright (C) 1995 Microsoft Corporation. All Rights Reserved.
*
* File: ddmm.cpp
* Content: Routines for using DirectDraw on a multimonitor system
*
***************************************************************************/
#ifdef __cplusplus
extern "C" { /* Assume C declarations for C++ */
#endif /* __cplusplus */
IDirectDraw * DirectDrawCreateFromDevice(LPSTR szDevice);
IDirectDraw * DirectDrawCreateFromWindow(HWND hwnd);
int DirectDrawDeviceFromWindow(HWND hwnd, LPSTR szDevice, RECT*prc);
#ifdef __cplusplus
}
#endif /* __cplusplus */

View file

@ -1,24 +0,0 @@
/*==========================================================================
*
* Copyright (C) 1998 Microsoft Corporation. All Rights Reserved.
*
* File: ddutil.cpp
* Content: Routines for loading bitmap and palettes from resources
*
***************************************************************************/
#ifdef __cplusplus
extern "C" { /* Assume C declarations for C++ */
#endif /* __cplusplus */
extern IDirectDrawPalette *DDLoadPalette(IDirectDraw4 *pdd, LPCSTR szBitmap);
extern IDirectDrawSurface4 *DDLoadBitmap(IDirectDraw4 *pdd, LPCSTR szBitmap, int dx, int dy);
extern HRESULT DDReLoadBitmap(IDirectDrawSurface4 *pdds, LPCSTR szBitmap);
extern HRESULT DDCopyBitmap(IDirectDrawSurface4 *pdds, HBITMAP hbm, int x, int y, int dx, int dy);
extern DWORD DDColorMatch(IDirectDrawSurface4 *pdds, COLORREF rgb);
extern HRESULT DDSetColorKey(IDirectDrawSurface4 *pdds, COLORREF rgb);
#ifdef __cplusplus
}
#endif /* __cplusplus */

View file

@ -1,24 +0,0 @@
/*==========================================================================
*
* Copyright (C) 1995 Microsoft Corporation. All Rights Reserved.
*
* File: ddutil.cpp
* Content: Routines for loading bitmap and palettes from resources
*
***************************************************************************/
#ifdef __cplusplus
extern "C" { /* Assume C declarations for C++ */
#endif /* __cplusplus */
extern IDirectDrawPalette * DDLoadPalette2(IDirectDraw2 *pdd, LPCSTR szBitmap);
extern IDirectDrawSurface3 * DDLoadBitmap2(IDirectDraw2 *pdd, LPCSTR szBitmap, int dx, int dy);
extern HRESULT DDReLoadBitmap2(IDirectDrawSurface3 *pdds, LPCSTR szBitmap);
extern HRESULT DDCopyBitmap2(IDirectDrawSurface3 *pdds, HBITMAP hbm, int x, int y, int dx, int dy);
extern DWORD DDColorMatch2(IDirectDrawSurface3 *pdds, COLORREF rgb);
extern HRESULT DDSetColorKey2(IDirectDrawSurface3 *pdds, COLORREF rgb);
#ifdef __cplusplus
}
#endif /* __cplusplus */

View file

@ -1,216 +0,0 @@
/*==========================================================================
*
* Copyright (C) 1995 Microsoft Corporation. All Rights Reserved.
*
* File: dsutil.cpp
* Content: Routines for dealing with sounds from resources
*
*
***************************************************************************/
#ifdef __cplusplus
extern "C" {
#endif
///////////////////////////////////////////////////////////////////////////////
//
// DSLoadSoundBuffer Loads an IDirectSoundBuffer from a Win32 resource in
// the current application.
//
// Params:
// pDS -- Pointer to an IDirectSound that will be used to create
// the buffer.
//
// lpName -- Name of WAV resource to load the data from. Can be a
// resource id specified using the MAKEINTRESOURCE macro.
//
// Returns an IDirectSoundBuffer containing the wave data or NULL on error.
//
// example:
// in the application's resource script (.RC file)
// Turtle WAV turtle.wav
//
// some code in the application:
// IDirectSoundBuffer *pDSB = DSLoadSoundBuffer(pDS, "Turtle");
//
// if (pDSB)
// {
// IDirectSoundBuffer_Play(pDSB, 0, 0, DSBPLAY_TOEND);
// /* ... */
//
///////////////////////////////////////////////////////////////////////////////
IDirectSoundBuffer *DSLoadSoundBuffer(IDirectSound *pDS, LPCTSTR lpName);
///////////////////////////////////////////////////////////////////////////////
//
// DSReloadSoundBuffer Reloads an IDirectSoundBuffer from a Win32 resource in
// the current application. normally used to handle
// a DSERR_BUFFERLOST error.
// Params:
// pDSB -- Pointer to an IDirectSoundBuffer to be reloaded.
//
// lpName -- Name of WAV resource to load the data from. Can be a
// resource id specified using the MAKEINTRESOURCE macro.
//
// Returns a BOOL indicating whether the buffer was successfully reloaded.
//
// example:
// in the application's resource script (.RC file)
// Turtle WAV turtle.wav
//
// some code in the application:
// TryAgain:
// HRESULT hres = IDirectSoundBuffer_Play(pDSB, 0, 0, DSBPLAY_TOEND);
//
// if (FAILED(hres))
// {
// if ((hres == DSERR_BUFFERLOST) &&
// DSReloadSoundBuffer(pDSB, "Turtle"))
// {
// goto TryAgain;
// }
// /* deal with other errors... */
// }
//
///////////////////////////////////////////////////////////////////////////////
BOOL DSReloadSoundBuffer(IDirectSoundBuffer *pDSB, LPCTSTR lpName);
///////////////////////////////////////////////////////////////////////////////
//
// DSGetWaveResource Finds a WAV resource in a Win32 module.
//
// Params:
// hModule -- Win32 module handle of module containing WAV resource.
// Pass NULL to indicate current application.
//
// lpName -- Name of WAV resource to load the data from. Can be a
// resource id specified using the MAKEINTRESOURCE macro.
//
// ppWaveHeader-- Optional pointer to WAVEFORMATEX * to receive a pointer to
// the WAVEFORMATEX header in the specified WAV resource.
// Pass NULL if not required.
//
// ppbWaveData -- Optional pointer to BYTE * to receive a pointer to the
// waveform data in the specified WAV resource. Pass NULL if
// not required.
//
// pdwWaveSize -- Optional pointer to DWORD to receive the size of the
// waveform data in the specified WAV resource. Pass NULL if
// not required.
//
// Returns a BOOL indicating whether a valid WAV resource was found.
//
///////////////////////////////////////////////////////////////////////////////
BOOL DSGetWaveResource(HMODULE hModule, LPCTSTR lpName,
WAVEFORMATEX **ppWaveHeader, BYTE **ppbWaveData, DWORD *pdwWaveSize);
///////////////////////////////////////////////////////////////////////////////
//
// HSNDOBJ Handle to a SNDOBJ object.
//
// SNDOBJs are implemented in dsutil as an example layer built on top
// of DirectSound.
//
// A SNDOBJ is generally used to manage individual
// sounds which need to be played multiple times concurrently. A
// SNDOBJ represents a queue of IDirectSoundBuffer objects which
// all refer to the same buffer memory.
//
// A SNDOBJ also automatically reloads the sound resource when
// DirectSound returns a DSERR_BUFFERLOST
//
///////////////////////////////////////////////////////////////////////////////
#ifndef _HSNDOBJ_DEFINED
DECLARE_HANDLE32(HSNDOBJ);
#endif
///////////////////////////////////////////////////////////////////////////////
//
// SndObjCreate Loads a SNDOBJ from a Win32 resource in
// the current application.
//
// Params:
// pDS -- Pointer to an IDirectSound that will be used to create
// the SNDOBJ.
//
// lpName -- Name of WAV resource to load the data from. Can be a
// resource id specified using the MAKEINTRESOURCE macro.
//
// iConcurrent -- Integer representing the number of concurrent playbacks of
// to plan for. Attempts to play more than this number will
// succeed but will restart the least recently played buffer
// even if it is not finished playing yet.
//
// Returns an HSNDOBJ or NULL on error.
//
// NOTES:
// SNDOBJs automatically restore and reload themselves as required.
//
///////////////////////////////////////////////////////////////////////////////
HSNDOBJ SndObjCreate(IDirectSound *pDS, LPCTSTR lpName, int iConcurrent);
///////////////////////////////////////////////////////////////////////////////
//
// SndObjDestroy Frees a SNDOBJ and releases all of its buffers.
//
// Params:
// hSO -- Handle to a SNDOBJ to free.
//
///////////////////////////////////////////////////////////////////////////////
void SndObjDestroy(HSNDOBJ hSO);
///////////////////////////////////////////////////////////////////////////////
//
// SndObjPlay Plays a buffer in a SNDOBJ.
//
// Params:
// hSO -- Handle to a SNDOBJ to play a buffer from.
//
// dwPlayFlags -- Flags to pass to IDirectSoundBuffer::Play. It is not
// legal to play an SndObj which has more than one buffer
// with the DSBPLAY_LOOPING flag. Pass 0 to stop playback.
//
///////////////////////////////////////////////////////////////////////////////
BOOL SndObjPlay(HSNDOBJ hSO, DWORD dwPlayFlags);
///////////////////////////////////////////////////////////////////////////////
//
// SndObjStop Stops one or more buffers in a SNDOBJ.
//
// Params:
// hSO -- Handle to a SNDOBJ to play a buffer from.
//
///////////////////////////////////////////////////////////////////////////////
BOOL SndObjStop(HSNDOBJ hSO);
///////////////////////////////////////////////////////////////////////////////
//
// SndObjGetFreeBuffer returns one of the cloned buffers that is
// not currently playing
//
// Params:
// hSO -- Handle to a SNDOBJ
//
// NOTES:
// This function is provided so that callers can set things like pan etc
// before playing the buffer.
//
// EXAMPLE:
// ...
//
///////////////////////////////////////////////////////////////////////////////
IDirectSoundBuffer *SndObjGetFreeBuffer(HSNDOBJ hSO);
///////////////////////////////////////////////////////////////////////////////
//
// helper routines
//
///////////////////////////////////////////////////////////////////////////////
BOOL DSFillSoundBuffer(IDirectSoundBuffer *pDSB, BYTE *pbWaveData, DWORD dwWaveSize);
BOOL DSParseWaveResource(void *pvRes, WAVEFORMATEX **ppWaveHeader, BYTE **ppbWaveData, DWORD *pdwWaveSize);
#ifdef __cplusplus
}
#endif

View file

@ -1,26 +0,0 @@
/*==========================================================================
*
* Copyright (C) 1995 Microsoft Corporation. All Rights Reserved.
*
* File: lbprintf.h
* Content: list box printf header file
*
***************************************************************************/
#ifndef __LBPRINTF_INCLUDED__
#define __LBPRINTF_INCLUDED__
#ifdef __cplusplus
extern "C" {
#endif
extern void LBCreate( HWND hWnd, DWORD pos );
extern void LBSize( DWORD dwWidth, DWORD dwHeight );
extern void LBClear( void );
extern void __cdecl LBPrintf( LPSTR fmt, ... );
extern void __cdecl LBPrintfDDRC( HRESULT rc, LPSTR fmt, ... );
#ifdef __cplusplus
}
#endif
#endif

View file

@ -1,32 +0,0 @@
//{{NO_DEPENDENCIES}}
// Microsoft Developer Studio generated include file.
// Used by ddenum.rc
//
#define IDI_MAIN_ICON 101
#define IDD_DRIVERINFO 102
#define IDC_PREV 1001
#define IDC_NEXT 1002
#define IDC_DEVICEID 1003
#define IDC_VERSION 1004
#define IDC_DESCRIPTION 1005
#define IDC_FILENAME 1006
#define IDC_COUNT 1007
#define IDC_GUID 1010
#define IDC_DWVENDORID 1012
#define IDC_DWDEVICEID 1014
#define IDC_DWSUBSYS 1015
#define IDC_DWREVISION 1016
#define IDC_RADIO_DEVICE 1018
#define IDC_RADIO_HOST 1019
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NO_MFC 1
#define _APS_NEXT_RESOURCE_VALUE 103
#define _APS_NEXT_COMMAND_VALUE 40001
#define _APS_NEXT_CONTROL_VALUE 1020
#define _APS_NEXT_SYMED_VALUE 103
#endif
#endif

View file

@ -1,383 +0,0 @@
//-----------------------------------------------------------------------------
// File: UserDlg.cpp
//
// Desc: Support functions for the user select driver dialog.
// Note: Since this code is destined for a static link library, the
// dialog dox is constructed manually. Otherwise, we would use a resource
// and save many lines of code. Manually constructing dialog boxes is not
// trivial and there are many issues (unicode, dword alignment, etc.)
// involved.
//
//
// Copyright (c) 1997-1998 Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#include <tchar.h>
#include "D3DEnum.h"
#include <stdio.h>
#include "d3dutil.h"
//-----------------------------------------------------------------------------
// Constants and function prototypes for the user select driver dialog
//-----------------------------------------------------------------------------
#define IDC_STATIC 0xffff
#define IDC_DRIVER_COMBO 1000
#define IDC_DEVICE_COMBO 1001
#define IDC_MODE_COMBO 1002
//-----------------------------------------------------------------------------
// External variables (declared in the D3DEnum.cpp file)
//-----------------------------------------------------------------------------
extern D3DEnum_DriverInfo* g_pCurrentDriver; // The selected DD driver
//-----------------------------------------------------------------------------
// Name: CopyToWideChar
//-----------------------------------------------------------------------------
static VOID CopyToWideChar( WCHAR** pstrOut, LPTSTR strIn )
{
DWORD dwLen = lstrlen( strIn );
WCHAR* strOut = *pstrOut;
#ifdef UNICODE // Copy Unicode to Unicode
_wcsncpy( strOut, strIn, dwLen );
strOut[dwLen] = L'\0';
#else // Copy Ansi to Unicode
dwLen = MultiByteToWideChar( CP_ACP, 0, strIn, dwLen, strOut, dwLen );
strOut[dwLen++] = L'\0'; // Add the null terminator
#endif
*pstrOut += dwLen;
}
//-----------------------------------------------------------------------------
// Name: AddDialogControl()
// Desc: Internal function to help build the user select dialog
//-----------------------------------------------------------------------------
static VOID AddDialogControl( WORD** pp, DWORD dwStyle, SHORT x, SHORT y,
SHORT cx, SHORT cy, WORD id,
LPTSTR strClassName, LPTSTR strTitle )
{
// DWORD align the current ptr
DLGITEMTEMPLATE* p = (DLGITEMTEMPLATE*)(((((ULONG)(*pp))+3)>>2)<<2);
p->style = dwStyle | WS_CHILD | WS_VISIBLE;
p->dwExtendedStyle = 0L;
p->x = x;
p->y = y;
p->cx = cx;
p->cy = cy;
p->id = id;
*pp = (WORD*)(++p); // Advance ptr
CopyToWideChar( (WCHAR**)pp, strClassName ); // Set Class name
CopyToWideChar( (WCHAR**)pp, strTitle ); // Set Title
(*pp)++; // Skip Extra Stuff
}
//-----------------------------------------------------------------------------
// Name: _BuildUserSelectDialog()
// Desc: Internal function to build the user select dialog
//-----------------------------------------------------------------------------
DLGTEMPLATE* _BuildDriverSelectTemplate()
{
// Allocate ample memory for building the template
DLGTEMPLATE* pDlgTemplate = new DLGTEMPLATE[50];
if( NULL == pDlgTemplate )
return NULL;
ZeroMemory( pDlgTemplate, 50*sizeof(DLGTEMPLATE) );
// Fill in the DLGTEMPLATE info
DLGTEMPLATE* pdt = pDlgTemplate;
pdt->style = DS_MODALFRAME | DS_NOIDLEMSG | DS_SETFOREGROUND |
DS_3DLOOK | DS_CENTER | WS_POPUP | WS_VISIBLE |
WS_CAPTION | WS_SYSMENU | DS_SETFONT;
pdt->dwExtendedStyle = 0L;
pdt->cdit = 8;
pdt->x = 0;
pdt->y = 0;
pdt->cx = 179;
pdt->cy = 84;
// Add menu array, class array, dlg title, font size and font name
WORD* pw = (WORD*)(++pdt);
*pw++ = L'\0'; // Set Menu array to nothing
*pw++ = L'\0'; // Set Class array to nothing
CopyToWideChar( (WCHAR**)&pw, TEXT( "Select New Direct3D Driver" ) ); // Dlg title
*pw++ = 8; // Font Size
CopyToWideChar( (WCHAR**)&pw, TEXT("Arial") ); // Font Name
// Add the okay button
AddDialogControl( &pw, BS_PUSHBUTTON | WS_TABSTOP, 65, 65, 51, 14,
IDOK, TEXT("BUTTON"), TEXT("OK") );
// Add the cancel button
AddDialogControl( &pw, BS_PUSHBUTTON | WS_TABSTOP, 123, 65, 51, 14,
IDCANCEL, TEXT("BUTTON"), TEXT("Cancel") );
// Add the driver select combobox
AddDialogControl( &pw, CBS_DROPDOWNLIST | WS_VSCROLL | WS_TABSTOP,
36, 5, 138, 45,
IDC_DRIVER_COMBO, TEXT("COMBOBOX"), TEXT("") );
// Add the device select combobox
AddDialogControl( &pw, CBS_DROPDOWNLIST | WS_VSCROLL | WS_TABSTOP,
36, 24, 138, 45,
IDC_DEVICE_COMBO, TEXT("COMBOBOX"), TEXT("") );
// Add the mode select combobox
AddDialogControl( &pw, CBS_DROPDOWNLIST | WS_VSCROLL | WS_TABSTOP,
36, 44, 138, 45,
IDC_MODE_COMBO, TEXT("COMBOBOX"), TEXT("") );
// Add the "Driver:" text
AddDialogControl( &pw, SS_LEFT, 5, 5, 22, 13,
IDC_STATIC, TEXT("STATIC"), TEXT("Driver:") );
// Add the "Device:" text
AddDialogControl( &pw, SS_LEFT, 5, 24, 25, 13,
IDC_STATIC, TEXT("STATIC"), TEXT("Device:") );
// Add the "Mode:" text
AddDialogControl( &pw, SS_LEFT, 5, 44, 22, 13,
IDC_STATIC, TEXT("STATIC"), TEXT("Mode:") );
return pDlgTemplate;
}
//-----------------------------------------------------------------------------
// Name: UpdateComboBoxesContent()
// Desc: Builds the list of drivers, devices and modes for the combo boxes
// in the driver select dialog box.
//-----------------------------------------------------------------------------
static VOID UpdateComboBoxesContent( HWND hDlg,
D3DEnum_DriverInfo** ppCurrentDriver,
D3DEnum_DeviceInfo** ppCurrentDevice,
D3DEnum_ModeInfo** ppCurrentMode,
BOOL bWindowed )
{
// Check the parameters
if( (NULL==ppCurrentDriver) || (NULL==ppCurrentDevice) ||
(NULL==ppCurrentMode) )
return;
// If the specified driver is NULL, use the first one in the list
if( NULL == *ppCurrentDriver)
(*ppCurrentDriver) = D3DEnum_GetFirstDriver();
// If the specified device is NULL, use the first one in the list
if( NULL == *ppCurrentDevice)
(*ppCurrentDevice) = (*ppCurrentDriver)->pFirstDevice;
// Reset the content in each of the combo boxes
SendDlgItemMessage( hDlg, IDC_DRIVER_COMBO, CB_RESETCONTENT, 0, 0 );
SendDlgItemMessage( hDlg, IDC_DEVICE_COMBO, CB_RESETCONTENT, 0, 0 );
SendDlgItemMessage( hDlg, IDC_MODE_COMBO, CB_RESETCONTENT, 0, 0 );
// Build the list of drivers for the combo box
for( D3DEnum_DriverInfo* pDriver = D3DEnum_GetFirstDriver(); pDriver;
pDriver = pDriver->pNext )
{
// Add driver desc to the combo box
DWORD dwItem = SendDlgItemMessage( hDlg, IDC_DRIVER_COMBO,
CB_ADDSTRING, 0, (LPARAM)pDriver->strDesc );
// Associate DriverInfo ptr with the item in the combo box
SendDlgItemMessage( hDlg, IDC_DRIVER_COMBO, CB_SETITEMDATA,
(WPARAM)dwItem, (LPARAM)pDriver );
// If this is the current driver, set is as the current selection
if( pDriver == (*ppCurrentDriver) )
SendDlgItemMessage( hDlg, IDC_DRIVER_COMBO, CB_SETCURSEL,
(WPARAM)dwItem, 0L );
}
// Build the list of devices for the combo box
for( D3DEnum_DeviceInfo* pDevice = (*ppCurrentDriver)->pFirstDevice; pDevice;
pDevice = pDevice->pNext )
{
// Add device name to the combo box
DWORD dwItem = SendDlgItemMessage( hDlg, IDC_DEVICE_COMBO,
CB_ADDSTRING, 0, (LPARAM)pDevice->strName );
// Associate DeviceInfo ptr with the item in the combo box
SendDlgItemMessage( hDlg, IDC_DEVICE_COMBO, CB_SETITEMDATA,
(WPARAM)dwItem, (LPARAM)pDevice );
// If this is the current device, set this as the current selection
if( pDevice == (*ppCurrentDevice) )
SendDlgItemMessage( hDlg, IDC_DEVICE_COMBO, CB_SETCURSEL,
(WPARAM)dwItem, 0L );
}
if( (*ppCurrentDriver)->ddDriverCaps.dwCaps2 & DDCAPS2_CANRENDERWINDOWED
&& ( NULL == (*ppCurrentDriver)->pGUID )
&& (*ppCurrentDevice)->bCompatbileWithDesktop )
{
// Add windowed mode to the combo box of available modes
DWORD dwItem = SendDlgItemMessage( hDlg, IDC_MODE_COMBO,
CB_ADDSTRING, 0, (LPARAM)TEXT("Windowed mode") );
// Associate ModeInfo ptr with the item in the combo box
SendDlgItemMessage( hDlg, IDC_MODE_COMBO, CB_SETITEMDATA,
(WPARAM)dwItem, (LPARAM)NULL );
// If the current device is windowed, set this as current
if( bWindowed )
SendDlgItemMessage( hDlg, IDC_MODE_COMBO, CB_SETCURSEL,
(WPARAM)dwItem, 0L );
}
// Build the list of modes for the combo box
for( D3DEnum_ModeInfo* pMode = (*ppCurrentDevice)->pFirstMode; pMode;
pMode = pMode->pNext )
{
// Add mode desc to the combo box
DWORD dwItem = SendDlgItemMessage( hDlg, IDC_MODE_COMBO,
CB_ADDSTRING, 0,
(LPARAM)pMode->strDesc );
// Associate ModeInfo ptr with the item in the combo box
SendDlgItemMessage( hDlg, IDC_MODE_COMBO, CB_SETITEMDATA,
(WPARAM)dwItem, (LPARAM)pMode );
// If this is the current mode, set is as the current selection
if( !bWindowed && ( pMode == (*ppCurrentMode) ) )
SendDlgItemMessage( hDlg, IDC_MODE_COMBO, CB_SETCURSEL,
(WPARAM)dwItem, 0L );
}
}
//-----------------------------------------------------------------------------
// Name: _DriverSelectProc()
// Desc: Windows message handling function for the driver select dialog
//-----------------------------------------------------------------------------
BOOL CALLBACK _DriverSelectProc( HWND hDlg, UINT uiMsg, WPARAM wParam,
LPARAM lParam )
{
static D3DEnum_DriverInfo *pOldDriver, *pNewDriver;
static D3DEnum_DeviceInfo *pOldDevice, *pNewDevice;
static D3DEnum_ModeInfo *pOldMode, *pNewMode;
static BOOL bOldWindowed, bNewWindowed;
// Handle the initialization message
if( WM_INITDIALOG == uiMsg )
{
// Setup temp storage pointers for dialog
pNewDriver = pOldDriver = g_pCurrentDriver;
pNewDevice = pOldDevice = pOldDriver->pCurrentDevice;
pNewMode = pOldMode = pOldDevice->pCurrentMode;
bNewWindowed = bOldWindowed = pOldDevice->bWindowed;
UpdateComboBoxesContent( hDlg, &pOldDriver, &pOldDevice,
&pOldMode, bOldWindowed );
return TRUE;
}
if( WM_COMMAND == uiMsg )
{
// Handle the case when the user hits the OK button
if( IDOK == LOWORD(wParam) )
{
// Check if any of the options were changed
if( ( pOldDriver != pNewDriver ) || ( pOldDevice != pNewDevice ) ||
( pOldMode != pNewMode ) || ( bOldWindowed != bNewWindowed ) )
{
// Set actual ptrs from the temp ptrs used for the dialog
g_pCurrentDriver = pNewDriver;
g_pCurrentDriver->pCurrentDevice = pNewDevice;
g_pCurrentDriver->pCurrentDevice->pCurrentMode = pNewMode;
g_pCurrentDriver->pCurrentDevice->bWindowed = bNewWindowed;
EndDialog( hDlg, IDOK );
return TRUE;
}
else
{
EndDialog( hDlg, IDCANCEL );
return TRUE;
}
}
// Handle the case when the user hits the Cancel button
else if( IDCANCEL == LOWORD(wParam) )
{
EndDialog( hDlg, IDCANCEL );
return TRUE;
}
// Handle the case when the user chooses an item in the combo boxes.
else if( CBN_SELENDOK == HIWORD(wParam) )
{
DWORD dwIndex = SendMessage( (HWND)lParam, CB_GETCURSEL,
0, 0 );
LONG pNewObject = SendMessage( (HWND)lParam, CB_GETITEMDATA,
dwIndex, 0 );
if( (CB_ERR==dwIndex) )
return TRUE;
// Handle the case where one of these may have changed. The
// combo boxes will need to be updated to reflect the changes.
switch( LOWORD( wParam ) )
{
case IDC_DRIVER_COMBO:
if( pNewObject && pNewObject != (LONG)pNewDriver )
{
pNewDriver = (D3DEnum_DriverInfo*)pNewObject;
pNewDevice = pNewDriver->pCurrentDevice;;
pNewMode = pNewDevice->pCurrentMode;
bNewWindowed = pNewDevice->bWindowed;
}
break;
case IDC_DEVICE_COMBO:
if( pNewObject && pNewObject != (LONG)pNewDevice )
{
pNewDevice = (D3DEnum_DeviceInfo*)pNewObject;
pNewMode = pNewDevice->pCurrentMode;
bNewWindowed = pNewDevice->bWindowed;
}
break;
case IDC_MODE_COMBO:
if( pNewObject )
{
pNewMode = (D3DEnum_ModeInfo*)pNewObject;
bNewWindowed = FALSE;
}
else
bNewWindowed = TRUE;
break;
}
UpdateComboBoxesContent( hDlg, &pNewDriver, &pNewDevice,
&pNewMode, bNewWindowed );
return TRUE;
}
}
return FALSE;
}

File diff suppressed because it is too large Load diff

Binary file not shown.

Before

Width:  |  Height:  |  Size: 66 KiB

View file

@ -1,121 +0,0 @@
/*
THE COMPUTER CODE CONTAINED HEREIN IS THE SOLE PROPERTY OF PARALLAX
SOFTWARE CORPORATION ("PARALLAX"). PARALLAX, IN DISTRIBUTING THE CODE TO
END-USERS, AND SUBJECT TO ALL OF THE TERMS AND CONDITIONS HEREIN, GRANTS A
ROYALTY-FREE, PERPETUAL LICENSE TO SUCH END-USERS FOR USE BY SUCH END-USERS
IN USING, DISPLAYING, AND CREATING DERIVATIVE WORKS THEREOF, SO LONG AS
SUCH USE, DISPLAY OR CREATION IS FOR NON-COMMERCIAL, ROYALTY OR REVENUE
FREE PURPOSES. IN NO EVENT SHALL THE END-USER USE THE COMPUTER CODE
CONTAINED HEREIN FOR REVENUE-BEARING PURPOSES. THE END-USER UNDERSTANDS
AND AGREES TO THE TERMS HEREIN AND ACCEPTS THE SAME BY USE OF THIS FILE.
COPYRIGHT 1993-1998 PARALLAX SOFTWARE CORPORATION. ALL RIGHTS RESERVED.
*/
#ifndef _JOY_H
#define _JOY_H
#include "types.h"
#include "fix.h"
#define JOY_1_BUTTON_A 1
#define JOY_1_BUTTON_B 2
#define JOY_2_BUTTON_A 4
#define JOY_2_BUTTON_B 8
#define JOY_ALL_BUTTONS (1+2+4+8)
#define JOY_1_X_AXIS 1
#define JOY_1_Y_AXIS 2
#define JOY_1_R_AXIS 4
#define JOY_1_Z_AXIS 8
#define JOY_1_U_AXIS 16
#define JOY_1_V_AXIS 32
#define JOY_ALL_AXIS (1+2+4+8+16+32)
//#if 0
//#define JOY_2_X_AXIS 4
//#define JOY_2_Y_AXIS 8
//#define JOY_ALL_AXIS (1+2+4+8)
//#endif
#define JOY_POLL_RATE 0 // use minimum FIXME: is this what we want?
#define JOY_NUM_AXES 6
#define JOY_MAX_BUTTONS 20
//==========================================================================
// This initializes the joy and does a "quick" calibration which
// assumes the stick is centered and sets the minimum value to 0 and
// the maximum value to 2 times the centered reading. Returns 0 if no
// joystick was detected, 1 if everything is ok.
// joy_init() is called.
extern int joy_init();
extern void joy_close();
extern char joy_installed;
extern char joy_present;
//==========================================================================
// The following 3 routines can be used to zero in on better joy
// calibration factors. To use them, ask the user to hold the stick
// in either the upper left, lower right, or center and then have them
// press a key or button and then call the appropriate one of these
// routines, and it will read the stick and update the calibration factors.
// Usually, assuming that the stick was centered when joy_init was
// called, you really only need to call joy_set_lr, since the upper
// left position is usually always 0,0 on most joys. But, the safest
// bet is to do all three, or let the user choose which ones to set.
extern void joy_set_ul();
extern void joy_set_lr();
extern void joy_set_cen();
//==========================================================================
// This reads the joystick. X and Y will be between -128 and 127.
// Takes about 1 millisecond in the worst case when the stick
// is in the lower right hand corner. Always returns 0,0 if no stick
// is present.
extern void joy_get_pos( int *x, int *y );
//==========================================================================
// This just reads the buttons and returns their status. When bit 0
// is 1, button 1 is pressed, when bit 1 is 1, button 2 is pressed.
extern int joy_get_btns();
//==========================================================================
// This returns the number of times a button went either down or up since
// the last call to this function.
extern int joy_get_button_up_cnt( int btn );
extern int joy_get_button_down_cnt( int btn );
//==========================================================================
// This returns how long (in approximate milliseconds) that each of the
// buttons has been held down since the last call to this function.
// It is the total time... say you pressed it down for 3 ticks, released
// it, and held it down for 6 more ticks. The time returned would be 9.
extern fix joy_get_button_down_time( int btn );
extern ubyte joy_read_raw_buttons();
extern ubyte joystick_read_raw_axis( ubyte mask, int * axis );
extern void joy_flush();
extern ubyte joy_get_present_mask();
extern void joy_set_timer_rate(int max_value );
extern int joy_get_timer_rate();
extern int joy_get_button_state( int btn );
extern void joy_set_cen_fake(int channel);
extern ubyte joy_read_stick( ubyte masks, int *axis );
extern void joy_get_cal_vals(int *axis_min, int *axis_center, int *axis_max);
extern void joy_set_cal_vals(int *axis_min, int *axis_center, int *axis_max);
extern void joy_set_btn_values( int btn, int state, fix timedown, int downcount, int upcount );
extern int joy_get_scaled_reading( int raw, int axn );
extern void joy_set_slow_reading( int flag );
extern int JOY_PORT;
extern int joy_deadzone;
#endif

View file

@ -1,223 +0,0 @@
/*
THE COMPUTER CODE CONTAINED HEREIN IS THE SOLE PROPERTY OF PARALLAX
SOFTWARE CORPORATION ("PARALLAX"). PARALLAX, IN DISTRIBUTING THE CODE TO
END-USERS, AND SUBJECT TO ALL OF THE TERMS AND CONDITIONS HEREIN, GRANTS A
ROYALTY-FREE, PERPETUAL LICENSE TO SUCH END-USERS FOR USE BY SUCH END-USERS
IN USING, DISPLAYING, AND CREATING DERIVATIVE WORKS THEREOF, SO LONG AS
SUCH USE, DISPLAY OR CREATION IS FOR NON-COMMERCIAL, ROYALTY OR REVENUE
FREE PURPOSES. IN NO EVENT SHALL THE END-USER USE THE COMPUTER CODE
CONTAINED HEREIN FOR REVENUE-BEARING PURPOSES. THE END-USER UNDERSTANDS
AND AGREES TO THE TERMS HEREIN AND ACCEPTS THE SAME BY USE OF THIS FILE.
COPYRIGHT 1993-1998 PARALLAX SOFTWARE CORPORATION. ALL RIGHTS RESERVED.
*/
/*
* $Source: /cvsroot/dxx-rebirth/d2x-rebirth/arch/win32/include/key.h,v $
* $Revision: 1.1.1.1 $
* $Author: zicodxx $
* $Date: 2006/03/17 19:54:27 $
*
* Header for keyboard functions
*
* $Log: key.h,v $
* Revision 1.1.1.1 2006/03/17 19:54:27 zicodxx
* initial import
*
* Revision 1.2 2004/08/28 23:17:45 schaffner
* move old per-file change logs into new file ChangeLog-old
*
* Revision 1.1.1.1 2001/01/19 03:30:15 bradleyb
* Import of d2x-0.0.8
*
* Revision 1.1.1.1 1999/06/14 22:01:23 donut
* Import of d1x 1.37 source.
*
*/
#ifndef _KEY_H
#define _KEY_H
#include "fix.h"
#include "types.h"
#include <ctype.h> // For 'toupper'
//==========================================================================
// This installs the int9 vector and initializes the keyboard in buffered
// ASCII mode. key_close simply undoes that.
extern void key_init();
extern void key_close();
//==========================================================================
// These are configuration parameters to setup how the buffer works.
// set keyd_buffer_type to 0 for no key buffering.
// set it to 1 and it will buffer scancodes.
extern unsigned char keyd_buffer_type;
extern unsigned char keyd_repeat; // 1=allow repeating, 0=dont allow repeat
// keyd_editor_mode... 0=game mode, 1=editor mode.
// Editor mode makes key_down_time always return 0 if modifiers are down.
extern unsigned char keyd_editor_mode;
// Time in seconds when last key was pressed...
extern volatile int keyd_time_when_last_pressed;
//==========================================================================
// These are the "buffered" keypress routines. Use them by setting the
// "keyd_buffer_type" variable.
extern void key_flush(); // Clears the 256 char buffer
extern int key_checkch(); // Returns 1 if a char is waiting
extern int key_getch(); // Gets key if one waiting other waits for one.
extern int key_inkey(); // Gets key if one, other returns 0.
extern int key_inkey_time(fix *time); // Same as inkey, but returns the time the key was pressed down.
extern int key_peekkey(); // Same as inkey, but doesn't remove key from buffer.
extern unsigned char key_to_ascii(int keycode );
extern char *key_name(int keycode); // Convert keycode to the name of the key
extern void key_debug(); // Does an INT3
//==========================================================================
// These are the unbuffered routines. Index by the keyboard scancode.
// Set to 1 if the key is currently down, else 0
extern volatile unsigned char keyd_pressed[];
extern volatile unsigned char keyd_last_pressed;
extern volatile unsigned char keyd_last_released;
// Returns the seconds this key has been down since last call.
extern fix key_down_time(int scancode);
// Returns number of times key has went from up to down since last call.
extern unsigned int key_down_count(int scancode);
// Returns number of times key has went from down to up since last call.
extern unsigned int key_up_count(int scancode);
// Clears the times & counts used by the above functions
// Took out... use key_flush();
//void key_clear_times();
//void key_clear_counts();
extern char * key_text[256];
#define KEY_SHIFTED 0x100
#define KEY_ALTED 0x200
#define KEY_CTRLED 0x400
#define KEY_DEBUGGED 0x800
#define KEY_0 11
#define KEY_1 2
#define KEY_2 3
#define KEY_3 4
#define KEY_4 5
#define KEY_5 6
#define KEY_6 7
#define KEY_7 8
#define KEY_8 9
#define KEY_9 10
#define KEY_A 30
#define KEY_B 48
#define KEY_C 46
#define KEY_D 32
#define KEY_E 18
#define KEY_F 33
#define KEY_G 34
#define KEY_H 35
#define KEY_I 23
#define KEY_J 36
#define KEY_K 37
#define KEY_L 38
#define KEY_M 50
#define KEY_N 49
#define KEY_O 24
#define KEY_P 25
#define KEY_Q 16
#define KEY_R 19
#define KEY_S 31
#define KEY_T 20
#define KEY_U 22
#define KEY_V 47
#define KEY_W 17
#define KEY_X 45
#define KEY_Y 21
#define KEY_Z 44
#define KEY_MINUS 12
#define KEY_EQUAL 13
#define KEY_DIVIDE 43
#define KEY_SLASH 28
#define KEY_COMMA 51
#define KEY_PERIOD 52
#define KEY_SEMICOL 39
#define KEY_LBRACKET 26
#define KEY_RBRACKET 27
#define KEY_RAPOSTRO 40
#define KEY_LAPOSTRO 41
#define KEY_ESC 1
#define KEY_ENTER 28
#define KEY_BACKSP 14
#define KEY_TAB 15
#define KEY_SPACEBAR 57
#define KEY_NUMLOCK 69
#define KEY_SCROLLOCK 70
#define KEY_CAPSLOCK 58
#define KEY_LSHIFT 42
#define KEY_RSHIFT 54
#define KEY_LALT 56
#define KEY_RALT 194
#define KEY_LCTRL 29
#define KEY_RCTRL 157
#define KEY_F1 59
#define KEY_F2 60
#define KEY_F3 61
#define KEY_F4 62
#define KEY_F5 63
#define KEY_F6 64
#define KEY_F7 65
#define KEY_F8 66
#define KEY_F9 67
#define KEY_F10 68
#define KEY_F11 87
#define KEY_F12 88
#define KEY_PAD0 82
#define KEY_PAD1 79
#define KEY_PAD2 80
#define KEY_PAD3 81
#define KEY_PAD4 75
#define KEY_PAD5 76
#define KEY_PAD6 77
#define KEY_PAD7 71
#define KEY_PAD8 72
#define KEY_PAD9 73
#define KEY_PADMINUS 74
#define KEY_PADPLUS 78
#define KEY_PADPERIOD 83
#define KEY_PADDIVIDE 81
#define KEY_PADMULTIPLY 55
#define KEY_PADENTER 156
#define KEY_INSERT 210
#define KEY_HOME 209
#define KEY_PAGEUP 221
#define KEY_DELETE 211
#define KEY_END 217
#define KEY_PAGEDOWN 219
#define KEY_UP 200
#define KEY_DOWN 208
#define KEY_LEFT 203
#define KEY_RIGHT 205
#define KEY_PRINT_SCREEN 165
#define KEY_PAUSE 143
#endif

View file

@ -1,111 +0,0 @@
/*
THE COMPUTER CODE CONTAINED HEREIN IS THE SOLE PROPERTY OF PARALLAX
SOFTWARE CORPORATION ("PARALLAX"). PARALLAX, IN DISTRIBUTING THE CODE TO
END-USERS, AND SUBJECT TO ALL OF THE TERMS AND CONDITIONS HEREIN, GRANTS A
ROYALTY-FREE, PERPETUAL LICENSE TO SUCH END-USERS FOR USE BY SUCH END-USERS
IN USING, DISPLAYING, AND CREATING DERIVATIVE WORKS THEREOF, SO LONG AS
SUCH USE, DISPLAY OR CREATION IS FOR NON-COMMERCIAL, ROYALTY OR REVENUE
FREE PURPOSES. IN NO EVENT SHALL THE END-USER USE THE COMPUTER CODE
CONTAINED HEREIN FOR REVENUE-BEARING PURPOSES. THE END-USER UNDERSTANDS
AND AGREES TO THE TERMS HEREIN AND ACCEPTS THE SAME BY USE OF THIS FILE.
COPYRIGHT 1993-1998 PARALLAX SOFTWARE CORPORATION. ALL RIGHTS RESERVED.
*/
/*
* $Source: /cvsroot/dxx-rebirth/d2x-rebirth/arch/win32/include/mouse.h,v $
* $Revision: 1.1.1.1 $
* $Author: zicodxx $
* $Date: 2006/03/17 19:54:27 $
*
* Header for mouse functions
*
* $Log: mouse.h,v $
* Revision 1.1.1.1 2006/03/17 19:54:27 zicodxx
* initial import
*
* Revision 1.2 2004/08/28 23:17:45 schaffner
* move old per-file change logs into new file ChangeLog-old
*
* Revision 1.1.1.1 2001/01/19 03:30:15 bradleyb
* Import of d2x-0.0.8
*
* Revision 1.2 1999/10/09 05:04:34 donut
* added mouse_init and mouse_close declarations
*
* Revision 1.1.1.1 1999/06/14 22:01:24 donut
* Import of d1x 1.37 source.
*
*/
#ifndef MOUSE_H
#define MOUSE_H
#include "types.h"
#include "fix.h"
#define MOUSE_MAX_BUTTONS 11
#define MBTN_LEFT 0
#define MBTN_RIGHT 1
#define MBTN_MIDDLE 2
#define MBTN_Z_UP 3
#define MBTN_Z_DOWN 4
#define MBTN_PITCH_BACKWARD 5
#define MBTN_PITCH_FORWARD 6
#define MBTN_BANK_LEFT 7
#define MBTN_BANK_RIGHT 8
#define MBTN_HEAD_LEFT 9
#define MBTN_HEAD_RIGHT 10
#define MOUSE_LBTN 1
#define MOUSE_RBTN 2
#define MOUSE_MBTN 4
#undef NOMOUSE
#ifndef NOMOUSE
extern int mouse_init(int unused);
extern void mouse_close(void);
//========================================================================
// Check for mouse driver, reset driver if installed. returns number of
// buttons if driver is present.
extern int mouse_set_limits( int x1, int y1, int x2, int y2 );
extern void mouse_flush(); // clears all mice events...
//========================================================================
extern void mouse_get_pos( int *x, int *y);
extern void mouse_get_delta( int *dx, int *dy );
extern int mouse_get_btns();
extern void mouse_set_pos( int x, int y);
extern void mouse_get_cyberman_pos( int *x, int *y );
// Returns how long this button has been down since last call.
extern fix mouse_button_down_time(int button);
// Returns how many times this button has went down since last call.
extern int mouse_button_down_count(int button);
// Returns 1 if this button is currently down
extern int mouse_button_state(int button);
#else
// 'Neutered' functions... :-)
#define mouse_init(a) -1
#define mouse_set_limits(a,b,c,d) -1
#define mouse_flush()
#define mouse_close()
#define mouse_get_pos(a,b)
#define mouse_get_delta(a,b)
#define mouse_get_btns() 0
#define mouse_set_pos(a,b)
#define mouse_get_cyberman_pos(a,b)
#define mouse_button_down_time(a) 0
#define mouse_button_down_count(a) 0
#define mouse_button_state(a) 0
#endif
#endif

View file

@ -1,145 +0,0 @@
/*
THE COMPUTER CODE CONTAINED HEREIN IS THE SOLE PROPERTY OF PARALLAX
SOFTWARE CORPORATION ("PARALLAX"). PARALLAX, IN DISTRIBUTING THE CODE TO
END-USERS, AND SUBJECT TO ALL OF THE TERMS AND CONDITIONS HEREIN, GRANTS A
ROYALTY-FREE, PERPETUAL LICENSE TO SUCH END-USERS FOR USE BY SUCH END-USERS
IN USING, DISPLAYING, AND CREATING DERIVATIVE WORKS THEREOF, SO LONG AS
SUCH USE, DISPLAY OR CREATION IS FOR NON-COMMERCIAL, ROYALTY OR REVENUE
FREE PURPOSES. IN NO EVENT SHALL THE END-USER USE THE COMPUTER CODE
CONTAINED HEREIN FOR REVENUE-BEARING PURPOSES. THE END-USER UNDERSTANDS
AND AGREES TO THE TERMS HEREIN AND ACCEPTS THE SAME BY USE OF THIS FILE.
COPYRIGHT 1993-1998 PARALLAX SOFTWARE CORPORATION. ALL RIGHTS RESERVED.
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "mono.h"
#include "key.h"
#include "joy.h"
#include "timer.h"
#include "error.h"
#include "inferno.h"
#include "game.h"
#include "object.h"
#include "player.h"
#include "controls.h"
#include "joydefs.h"
#include "render.h"
#include "palette.h"
#include "newmenu.h"
#include "args.h"
#include "text.h"
#include "kconfig.h"
#include "digi.h"
#include "playsave.h"
int joydefs_calibrate_flag=0;
int Joy_is_Sidewinder=0; //not needed, but lots of main/* stuff use it
void joy_delay()
{
}
int joycal_message( char * title, char * text )
{
int i;
newmenu_item m[2];
m[0].type = NM_TYPE_TEXT; m[0].text = text;
m[1].type = NM_TYPE_MENU; m[1].text = TXT_OK;
i = newmenu_do( title, NULL, 2, m, NULL );
if ( i < 0 )
return 1;
return 0;
}
void joydefs_calibrate()
{
joycal_message("No Calibration", "calibration should be performed\nthrough windows");
return;
}
void joydef_menuset_1(int nitems, newmenu_item * items, int *last_key, int citem )
{
int i;
int oc_type = Config_control_type;
nitems = nitems;
last_key = last_key;
citem = citem;
for (i=0; i<3; i++ )
if (items[i].value) Config_control_type = i;
if (Config_control_type == 2) Config_control_type = CONTROL_MOUSE;
if ( (oc_type != Config_control_type) && (Config_control_type == CONTROL_THRUSTMASTER_FCS ) ) {
nm_messagebox( TXT_IMPORTANT_NOTE, 1, TXT_OK, TXT_FCS );
}
if (oc_type != Config_control_type) {
switch (Config_control_type) {
// case CONTROL_NONE:
case CONTROL_JOYSTICK:
case CONTROL_FLIGHTSTICK_PRO:
case CONTROL_THRUSTMASTER_FCS:
case CONTROL_GRAVIS_GAMEPAD:
// case CONTROL_MOUSE:
// case CONTROL_CYBERMAN:
joydefs_calibrate_flag = 1;
}
kc_set_controls();
}
}
extern ubyte kc_use_external_control;
extern ubyte kc_enable_external_control;
extern ubyte *kc_external_name;
void joydefs_config()
{
newmenu_item m[13];
int i, j, i1=0, nitems=7;
m[0].type = NM_TYPE_RADIO; m[0].text = "KEYBOARD"; m[0].value = 0; m[0].group = 0;
m[1].type = NM_TYPE_RADIO; m[1].text = "JOYSTICK"; m[1].value = 0; m[1].group = 0;
m[2].type = NM_TYPE_RADIO; m[2].text = "MOUSE"; m[2].value = 0; m[2].group = 0;
m[3].type = NM_TYPE_TEXT; m[3].text="";
m[4].type = NM_TYPE_MENU; m[4].text="CUSTOMIZE ABOVE";
m[5].type = NM_TYPE_MENU; m[5].text="CUSTOMIZE KEYBOARD";
m[6].type = NM_TYPE_MENU; m[6].text="CUSTOMIZE D1X KEYS";
do {
i = Config_control_type;
if(i==CONTROL_MOUSE) i = 2;
m[i].value=1;
i1 = newmenu_do1( NULL, TXT_CONTROLS, nitems, m, joydef_menuset_1, i1 );
//added 6-15-99 Owen Evans
for (j = 0; j <= 2; j++)
if (m[j].value)
Config_control_type = j;
i = Config_control_type;
if (Config_control_type == 2)
Config_control_type = CONTROL_MOUSE;
//end added - OE
switch(i1) {
case 4:
kconfig (i, m[i].text);
break;
case 5:
kconfig(0, "KEYBOARD");
break;
case 6:
kconfig(3, "D1X KEYS");
break;
}
} while(i1>-1);
}

View file

@ -1,482 +0,0 @@
/* $Id: key.c,v 1.1.1.1 2006/03/17 19:53:55 zicodxx Exp $ */
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <stdio.h>
#include <dinput.h>
//#include "inferno.h"
#include "fix.h"
#include "timer.h"
#include "key.h"
extern void PumpMessages(void);
// These are to kludge up a bit my slightly broken GCC directx port.
#ifndef E_FAIL
#define E_FAIL (HRESULT)0x80004005L
#endif
#ifndef SUCCEEDED
#define SUCCEEDED(a) ((HRESULT)(a) >= 0)
#endif
#ifndef S_OK
#define S_OK 0
#define S_FALSE 1
#endif
extern void PumpMessages(void);
volatile int keyd_time_when_last_pressed;
volatile unsigned char keyd_last_pressed;
volatile unsigned char keyd_last_released;
volatile unsigned char keyd_pressed [256];
unsigned char keyd_repeat;
unsigned char WMKey_Handler_Ready=0;
fix g_rgtimeDown [256];
fix g_rgtimeElapsed [256];
ULONG g_rgcDowns [256];
ULONG g_rgcUps [256];
char ascii_table[256];
char shifted_ascii_table[256];
LPDIRECTINPUT g_lpdi;
LPDIRECTINPUTDEVICE g_lpdidKeybd;
extern HWND g_hWnd;
typedef int KEYCODE;
#define KEY_BUFFER_SIZE 16
ULONG g_rgbKeyQueue [KEY_BUFFER_SIZE];
fix g_rgtimeQueue [KEY_BUFFER_SIZE];
ULONG g_rgbPressedQueue [KEY_BUFFER_SIZE];
ULONG iQueueStart = 0;
ULONG iQueueEnd = 0;
KEYCODE ShiftKeyCode (KEYCODE kcKey)
{
KEYCODE kcShifted;
if (keyd_pressed [kcKey])
{
kcShifted = kcKey;
// the key is down
if (keyd_pressed [KEY_LSHIFT] || keyd_pressed [KEY_RSHIFT])
{
kcShifted |= KEY_SHIFTED;
}
if (keyd_pressed [KEY_LCTRL] || keyd_pressed [KEY_RCTRL])
{
kcShifted |= KEY_CTRLED;
}
if (keyd_pressed [KEY_LALT] || keyd_pressed [KEY_RALT])
{
kcShifted |= KEY_ALTED;
}
}
else
{
// the key is UP!
kcShifted = 0;
}
return kcShifted;
}
BOOL SpaceInBuffer ()
{
if (iQueueStart == 0)
{
return iQueueEnd != KEY_BUFFER_SIZE - 1;
}
else
{
return iQueueEnd != iQueueStart - 1;
}
}
void FlushQueue (void)
{
iQueueStart = iQueueEnd = 0;
}
void PushKey (ULONG kcKey, fix timeDown)
{
if (SpaceInBuffer ())
{
g_rgbKeyQueue [iQueueEnd] = ShiftKeyCode(kcKey);
g_rgtimeQueue [iQueueEnd] = timeDown;
if (iQueueEnd ++ == KEY_BUFFER_SIZE)
{
iQueueEnd = 0;
}
}
}
BOOL PopKey (KEYCODE *piKey, fix *ptimeDown)
{
if (iQueueEnd != iQueueStart)
{
// there are items in the queue
if (piKey != NULL)
{
*piKey = g_rgbKeyQueue [iQueueStart];
}
if (ptimeDown != NULL)
{
*ptimeDown = g_rgbPressedQueue [iQueueStart];
}
if (iQueueStart ++ == KEY_BUFFER_SIZE)
{
iQueueStart = 0;
}
return TRUE;
}
else
{
return FALSE;
}
}
static BOOL EnsureInit (void)
{
if (g_lpdidKeybd == NULL)
{
key_init ();
}
return g_lpdidKeybd != NULL;
}
void key_close(void);
void key_init()
{
HRESULT hr;
// my kingdom, my kingdom for C++...
if (SUCCEEDED (hr = DirectInputCreate (GetModuleHandle (NULL), DIRECTINPUT_VERSION, &g_lpdi, NULL)))
{
if (SUCCEEDED (hr = IDirectInput_CreateDevice (g_lpdi, (void *)&GUID_SysKeyboard, &g_lpdidKeybd, NULL)))
{
DIPROPDWORD dipdw;
dipdw.diph.dwSize = sizeof (DIPROPDWORD);
dipdw.diph.dwHeaderSize = sizeof (DIPROPHEADER);
dipdw.diph.dwObj = 0;
dipdw.diph.dwHow = DIPH_DEVICE;
dipdw.dwData = 40;
if (SUCCEEDED (hr = IDirectInputDevice_SetDataFormat (g_lpdidKeybd, &c_dfDIKeyboard)) &&
SUCCEEDED (hr = IDirectInputDevice_SetCooperativeLevel (g_lpdidKeybd, g_hWnd, DISCL_NONEXCLUSIVE | DISCL_FOREGROUND)) &&
SUCCEEDED (hr = IDirectInputDevice_SetProperty (g_lpdidKeybd, DIPROP_BUFFERSIZE, &dipdw.diph)) &&
SUCCEEDED (hr = IDirectInputDevice_Acquire (g_lpdidKeybd)))
{
// fine
WMKey_Handler_Ready = 1;
// Clear the keyboard array
key_flush();
atexit(key_close);
}
else
{
IDirectInputDevice_Release (g_lpdidKeybd);
g_lpdidKeybd = NULL;
}
}
}
}
void key_close(void)
{
WMKey_Handler_Ready = 0;
if (g_lpdidKeybd != NULL)
{
IDirectInputDevice_Unacquire (g_lpdidKeybd);
IDirectInputDevice_Release (g_lpdidKeybd);
g_lpdidKeybd = NULL;
}
if (g_lpdi != NULL)
{
IDirectInput_Release (g_lpdi);
g_lpdi = NULL;
}
}
HRESULT ReadKey (DIDEVICEOBJECTDATA *pdidod)
{
DWORD cElements = 1;
HRESULT hr;
if (g_lpdidKeybd == NULL)
return E_FAIL;
hr = IDirectInputDevice_Acquire (g_lpdidKeybd);
if (SUCCEEDED (hr))
{
hr = IDirectInputDevice_GetDeviceData (
g_lpdidKeybd,
sizeof (*pdidod),
pdidod,
&cElements,
0);
if (SUCCEEDED (hr) && cElements != 1)
hr = E_FAIL;
}
return hr;
}
void UpdateState (DIDEVICEOBJECTDATA *pdidod)
{
KEYCODE kcKey = pdidod->dwOfs;
fix timeNow = timer_get_fixed_seconds ();
if (pdidod->dwData & 0x80)
{
keyd_pressed [kcKey] = 1;
keyd_last_pressed = kcKey;
g_rgtimeDown [kcKey] = keyd_time_when_last_pressed = timeNow;
g_rgcDowns [kcKey] ++;
PushKey (kcKey, keyd_time_when_last_pressed);
}
else
{
keyd_pressed [kcKey] = 0;
keyd_last_released = kcKey;
g_rgcUps [kcKey] ++;
g_rgtimeElapsed [kcKey] = timeNow - g_rgtimeDown [kcKey];
}
}
void keyboard_handler()
{
// static int peekmsgcount = 0;
DIDEVICEOBJECTDATA didod;
while (SUCCEEDED (ReadKey (&didod)))
{
UpdateState (&didod);
//added 02/20/99 by adb to prevent message overflow
//(this should probably go somewhere else...)
// if (++peekmsgcount == 64) // 64 = wild guess...
// {
// peekmsgcount = 0;
// }
//end additions
}
PumpMessages();
}
void key_flush()
{
if (EnsureInit ())
{
DWORD cElements = INFINITE;
ULONG kcKey;
// HRESULT hr =
IDirectInputDevice_GetDeviceData(
g_lpdidKeybd,
sizeof (DIDEVICEOBJECTDATA),
NULL,
&cElements,
0);
for (kcKey = 0; kcKey < 256; kcKey ++)
{
g_rgtimeElapsed [kcKey] = 0;
g_rgcDowns [kcKey] = 0;
g_rgcUps [kcKey] = 0;
keyd_pressed [kcKey] = 0;
}
FlushQueue ();
}
}
int key_getch()
{
KEYCODE kcKey;
keyboard_handler();
while (!PopKey (&kcKey, NULL))
{
keyboard_handler ();
}
return kcKey;
}
KEYCODE key_inkey_time(fix * pTime)
{
KEYCODE kcKey = 0;
keyboard_handler ();
PopKey (&kcKey, pTime);
return kcKey;
}
KEYCODE key_inkey ()
{
return key_inkey_time (NULL);
}
KEYCODE key_peekkey ()
{
keyboard_handler();
return 0;
}
int key_checkch()
{
return 1; // FIXME
}
unsigned char key_to_ascii(KEYCODE kcKey )
{
BOOL bShifted = kcKey & KEY_SHIFTED;
unsigned char ch;
kcKey &= ~KEY_SHIFTED;
if (kcKey <= 127)
{
if (bShifted)
{
ch = shifted_ascii_table [kcKey & 0xff];
}
else
{
ch = ascii_table [kcKey & 0xff];
}
}
else
{
ch = 255;
}
return ch;
}
// Returns the number of seconds this key has been down since last call.
fix key_down_time(KEYCODE kcKey)
{
ULONG timeElapsed;
keyboard_handler();
if ((kcKey<0) || (kcKey>127)) return 0;
if (keyd_pressed [kcKey])
{
fix timeNow = timer_get_fixed_seconds ();
timeElapsed = timeNow - g_rgtimeDown [kcKey];
g_rgtimeDown [kcKey] = timeNow;
}
else
{
timeElapsed = g_rgtimeElapsed [kcKey];
g_rgtimeElapsed [kcKey] = 0;
}
return timeElapsed;;
}
unsigned int key_down_count(KEYCODE kcKey)
{
int n;
keyboard_handler();
if ((kcKey < 0) || (kcKey > 127))
{
n = 0;
}
else
{
n = g_rgcDowns [kcKey];
g_rgcDowns [kcKey] = 0;
}
return n;
}
unsigned int key_up_count(KEYCODE kcKey)
{
int n;
keyboard_handler();
if ((kcKey < 0) || (kcKey > 127))
{
n = 0;
}
else
{
n = g_rgcUps [kcKey];
g_rgcUps [kcKey] = 0;
}
return n;
}
#define ___ ((char) 255)
char ascii_table[256] =
{
___, ___, '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', '=', ___, ___,
'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', '[', ']', ___, ___, 'a', 's',
'd', 'f', 'g', 'h', 'j', 'k', 'l', ';','\'', '`', ___,'\\', 'z', 'x', 'c', 'v',
'b', 'n', 'm', ',', '.', '/', ___, '*', ___, ' ', ___, ___, ___, ___, ___, ___,
___, ___, ___, ___, ___, ___, ___, '7', '8', '9', '-', '4', '5', '6', '+', '1',
'2', '3', '0', '.', ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___,
___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___,
___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___,
};
char shifted_ascii_table[256] =
{
___, ___, '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '+', ___, ___,
'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', '{', '}', ___, ___, 'A', 'S',
'D', 'F', 'G', 'H', 'J', 'K', 'L', ':','\"', '~', ___, '|', 'Z', 'X', 'C', 'V',
'B', 'N', 'M', '<', '>', '?', ___, '*', ___, ' ', ___, ___, ___, ___, ___, ___,
___, ___, ___, ___, ___, ___, ___, '&', '*', '(', '_', '$', '%', '^', '=', '!',
'@', '#', ')', '>', ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___,
___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___,
___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___,
};
#undef ___
char * key_text[256] = {
"","ESC","1","2","3","4","5","6","7","8","9","0","-",
"=","BSPC","TAB","Q","W","E","R","T","Y","U","I","O",
"P","[","]","ƒ","LCTRL","A","S","D","F",
"G","H","J","K","L",";","'","`",
"LSHFT","\\","Z","X","C","V","B","N","M",",",
".","/","RSHFT","PAD*","LALT","SPC",
"CPSLK","F1","F2","F3","F4","F5","F6","F7","F8","F9",
"F10","NMLCK","SCLK","PAD7","PAD8","PAD9","PAD-",
"PAD4","PAD5","PAD6","PAD+","PAD1","PAD2","PAD3","PAD0",
"PAD.","","","","F11","F12","","","","","","","","","",
"","","","","","","","","","","","","","","","","","","","",
"","","","","","","","","","","","","","","","","","","","",
"","","","","","","","","","","","","","","","","","",
"PADƒ","RCTRL","","","","","","","","","","","","","",
"","","","","","","","","","","PAD/","","","RALT","",
"","","","","","","","","","","","","","HOME","","PGUP",
"","<EFBFBD>","","","","END","","PGDN","INS",
"DEL","","","","","","","","","","","","","","","","","",
"","","","","","","","","","","","","","","","","","","","",
"","","","","","","" };
#if 0 // what was this? -- adb
"","","","HOME","UP","PGUP","","LEFT","","RGHT","","END","DOWN","PGDN","INS","DEL",
"","<EFBFBD>","","","","","?","","",
"","","","","","","","","","","","","","","","","","",
"","","","","","","","","","","","","","","","","","","","",
"","","","","","","" };
#endif

View file

@ -1,4 +0,0 @@
#include "pch.h"
#include <atlimpl.cpp>
CComModule _Module;

View file

@ -1,810 +0,0 @@
//-----------------------------------------------------------------------------
// File: VBuffer.cpp
//
// Desc: Example code showing how to use DirectX 6 vertex buffers.
//
// Note: This code uses the D3D Framework helper library.
//
//
// Copyright (c) 1997-1998 Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#include "pch.h"
#include "scene.h"
#include <stack>
#include "D3DTextr.h"
#include "D3DUtil.h"
#include "D3DMath.h"
#include "D3DFrame.h"
#include "texture.h"
extern CD3DFramework* g_pFramework;
extern BOOL g_bWindowed;
extern "C" {
#include "d3dhelp.h"
}
//-----------------------------------------------------------------------------
// Declare the application globals for use in WinMain.cpp
//-----------------------------------------------------------------------------
void Win32_SetupColor(void);
BOOL g_TrueColor;
int g_RShift, g_GShift, g_BShift;
int g_RBits6, g_GBits6, g_BBits6;
TCHAR* g_strAppTitle = TEXT( "Direct3D Descent" );
BOOL g_bAppUseZBuffer = FALSE;
BOOL g_bAppUseBackBuffer = TRUE;
LPDIRECT3DTEXTURE2 g_pd3dtLast;
BOOL g_bTransparentLast;
std::stack <D3DMATRIX> g_stkWorlds;
float g_fPSURed = 0.0f;
float g_fPSUGreen = 0.0f;
float g_fPSUBlue = 0.0f;
D3DLVERTEX g_rgVerts [16];
CTextureSet g_setTextures;
//-----------------------------------------------------------------------------
// Defines, constants, and global variables
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Function prototypes and global (or static) variables
//-----------------------------------------------------------------------------
HRESULT App_InitDeviceObjects( LPDIRECT3DDEVICE3, LPDIRECT3DVIEWPORT3 );
VOID App_DeleteDeviceObjects( LPDIRECT3DDEVICE3, LPDIRECT3DVIEWPORT3 );
//-----------------------------------------------------------------------------
// Name: App_OneTimeSceneInit()
// Desc: Called during initial app startup, this function performs all the
// permanent initialization.
//-----------------------------------------------------------------------------
HRESULT App_OneTimeSceneInit( HWND hWnd )
{
// Create some textures
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: App_InitDeviceObjects()
// Desc: Initialize scene objects.
//-----------------------------------------------------------------------------
HRESULT App_InitDeviceObjects( LPDIRECT3DDEVICE3 pd3dDevice,
LPDIRECT3DVIEWPORT3 pvViewport )
{
// Check parameters
if( NULL==pd3dDevice || NULL==pvViewport )
return E_INVALIDARG;
D3DVIEWPORT2 vdData;
ZeroMemory( &vdData, sizeof(D3DVIEWPORT2) );
vdData.dwSize = sizeof(vdData);
vdData.dwX = 0;
vdData.dwY = 0;
vdData.dwWidth = g_pFramework->m_dwRenderWidth;
vdData.dwHeight = 147 * g_pFramework->m_dwRenderHeight / 200;
vdData.dvMaxZ = 1.0f;
vdData.dvClipX = -1.0f;
vdData.dvClipY = (FLOAT) g_pFramework->m_dwRenderHeight / (FLOAT) g_pFramework->m_dwRenderWidth;
vdData.dvClipWidth = 2.0f;
vdData.dvClipHeight = 2.0f * vdData.dvClipY;
vdData.dvMinZ = 0.0f;
vdData.dvMaxZ = 1.0f;
// Set the parameters to the new viewport
if (FAILED (pvViewport->SetViewport2 (&vdData)))
{
DEBUG_MSG( TEXT("Error: Couldn't set the viewport data") );
return D3DFWERR_NOVIEWPORT;
}
// Get a ptr to the ID3D object to create VB's, materials and/or lights.
// Note: the Release() call just serves to decrease the ref count.
LPDIRECT3D3 pD3D;
if( FAILED( pd3dDevice->GetDirect3D( &pD3D ) ) )
return E_FAIL;
pD3D->Release();
// Get the device's caps bits
D3DDEVICEDESC ddHwDesc, ddSwDesc;
D3DUtil_InitDeviceDesc( ddHwDesc );
D3DUtil_InitDeviceDesc( ddSwDesc );
if( FAILED( pd3dDevice->GetCaps( &ddHwDesc, &ddSwDesc ) ) )
return E_FAIL;
D3DMATRIX matProj;
float fAspect = 1.0f;
D3DUtil_SetProjectionMatrix( matProj, g_PI/3, fAspect, 0.01f, 1000.0f );
pd3dDevice->SetTransform( D3DTRANSFORMSTATE_PROJECTION, &matProj );
pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE );
//pd3dDevice->SetTextureStageState( 0, D3DTSS_MINFILTER, D3DTFN_LINEAR );
//pd3dDevice->SetTextureStageState( 0, D3DTSS_MAGFILTER, D3DTFG_LINEAR );
pd3dDevice->SetRenderState (D3DRENDERSTATE_SPECULARENABLE, FALSE);
pd3dDevice->SetRenderState (D3DRENDERSTATE_DITHERENABLE, TRUE);
pd3dDevice->SetRenderState (D3DRENDERSTATE_TEXTUREPERSPECTIVE, TRUE);
pd3dDevice->SetRenderState (D3DRENDERSTATE_FILLMODE, D3DFILL_SOLID);
pd3dDevice->SetRenderState (D3DRENDERSTATE_ZENABLE, 0);
pd3dDevice->SetRenderState (D3DRENDERSTATE_CULLMODE, D3DCULL_NONE);
pd3dDevice->SetRenderState (D3DRENDERSTATE_COLORKEYENABLE, FALSE);
D3DMATRIX matID;
D3DUtil_SetIdentityMatrix (matID);
while (!g_stkWorlds.empty ())
g_stkWorlds.pop ();
g_stkWorlds.push (matID);
pd3dDevice->SetTransform( D3DTRANSFORMSTATE_WORLD, &matID );
g_setTextures.Initialize ();
g_bTransparentLast = FALSE;
g_pd3dtLast = NULL;
Win32_SetupColor();
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: App_FinalCleanup()
// Desc: Called before the app exits, this function gives the app the chance
// to cleanup after itself.
//-----------------------------------------------------------------------------
HRESULT App_FinalCleanup( LPDIRECT3DDEVICE3 pd3dDevice,
LPDIRECT3DVIEWPORT3 pvViewport)
{
App_DeleteDeviceObjects( pd3dDevice, pvViewport );
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: App_DeleteDeviceObjects()
// Desc: Called when the app is exitting, or the device is being changed,
// this function deletes any device dependant objects.
//-----------------------------------------------------------------------------
VOID App_DeleteDeviceObjects( LPDIRECT3DDEVICE3 pd3dDevice,
LPDIRECT3DVIEWPORT3 pvViewport)
{
D3DTextr_InvalidateAllTextures();
g_setTextures.Uninitialize ();
Win32_InvalidatePages();
Win32_SetupColor();
}
//----------------------------------------------------------------------------
// Name: App_RestoreSurfaces
// Desc: Restores any previously lost surfaces. Must do this for all surfaces
// (including textures) that the app created.
//----------------------------------------------------------------------------
HRESULT App_RestoreSurfaces()
{
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: App_ConfirmDevice()
// Desc: Called during device intialization, this code checks the device
// for some minimum set of capabilities
//-----------------------------------------------------------------------------
HRESULT App_ConfirmDevice( DDCAPS* pddDriverCaps,
D3DDEVICEDESC* pd3dDeviceDesc )
{
// Don't allow 3d Devices that don't support textures(Matrox Millenium)
if (!pd3dDeviceDesc->dwMaxTextureWidth)
return DDERR_INVALIDOBJECT;
return S_OK;
}
#define byte __BOGUS1
#define bool __BOGUS2
extern "C"
{
#include "types.h"
#include "grdef.h"
#include "..\main\segment.h"
#include "..\main\segpoint.h"
#include "..\main\object.h"
#include "..\3d\globvars.h"
#include "3d.h"
#include "palette.h"
}
#undef __BOGUS1
#undef __BOGUS2
LPDIRECT3DDEVICE3 g_pd3dDevice;
HRESULT App_StartFrame( LPDIRECT3DDEVICE3 pd3dDevice, LPDIRECT3DVIEWPORT3 pvViewport, D3DRECT* prcViewRect )
{
g_pd3dDevice = pd3dDevice;
HRESULT hResult;
hResult = pvViewport->Clear2 (1UL, prcViewRect, D3DCLEAR_TARGET, 0, 1.0f, 0);
// Begin the scene
hResult = pd3dDevice->BeginScene();
ASSERT (g_stkWorlds.size () == 1);
return hResult;
}
HRESULT App_EndFrame (void)
{
HRESULT hResult;
hResult = g_pd3dDevice->EndScene ();
ASSERT (g_stkWorlds.size () == 1);
return hResult;
}
extern "C" RGBQUAD w32lastrgb[256];
extern "C" void Win32_DoSetPalette (PALETTEENTRY *rgpe)
{
g_setTextures.SetPaletteEntries (rgpe);
for (int i = 0; i < 256; i++) {
w32lastrgb[i].rgbBlue = rgpe[i].peBlue;
w32lastrgb[i].rgbGreen = rgpe[i].peGreen;
w32lastrgb[i].rgbRed = rgpe[i].peRed;
}
}
extern "C" void Win32_DoGetPalette (PALETTEENTRY *rgpe)
{
g_setTextures.GetPaletteEntries (rgpe);
}
extern "C" int Win32_PaletteStepUp (int r, int g, int b)
{
if (g_setTextures.HasPalette ())
{
g_fPSURed = g_fPSUGreen = g_fPSUBlue = 0.0f;
return FALSE;
}
else
{
g_fPSURed = (float) r / 32.0f;
g_fPSUGreen = (float) g / 32.0f;
g_fPSUBlue = (float) b / 32.0f;
return TRUE;
}
}
D3DVECTOR g_vecRight, g_vecUp;
extern "C" void Win32_set_view_matrix ()
{
vms_vector *pPos = &View_position;
vms_matrix *pOrient = &View_matrix;
D3DVECTOR vecView;
vecView.x = (D3DVALUE) f2fl (pPos->x) / 10;
vecView.y = (D3DVALUE) f2fl (pPos->y) / 10;
vecView.z = (D3DVALUE) f2fl (pPos->z) / 10;
D3DMATRIX matView;
D3DVECTOR vecDir;
matView(0, 0) = g_vecRight.x = (D3DVALUE) f2fl (pOrient->rvec.x) / 10;
matView(1, 0) = g_vecRight.y = (D3DVALUE) f2fl (pOrient->rvec.y) / 10;
matView(2, 0) = g_vecRight.z = (D3DVALUE) f2fl (pOrient->rvec.z) / 10;
matView(0, 1) = g_vecUp.x = (D3DVALUE) f2fl (pOrient->uvec.x) / 10;
matView(1, 1) = g_vecUp.y = (D3DVALUE) f2fl (pOrient->uvec.y) / 10;
matView(2, 1) = g_vecUp.z = (D3DVALUE) f2fl (pOrient->uvec.z) / 10;
matView(0, 2) = vecDir.x = (D3DVALUE) f2fl (pOrient->fvec.x) / 10;
matView(1, 2) = vecDir.y = (D3DVALUE) f2fl (pOrient->fvec.y) / 10;
matView(2, 2) = vecDir.z = (D3DVALUE) f2fl (pOrient->fvec.z) / 10;
matView(3, 0) = -DotProduct (g_vecRight, vecView);
matView(3, 1) = -DotProduct (g_vecUp, vecView);
matView(3, 2) = -DotProduct (vecDir, vecView);
matView(0, 3) = matView(1, 3) = matView(2, 3) = 0.0f;
matView(3, 3) = 1.0f;
g_pd3dDevice->SetTransform( D3DTRANSFORMSTATE_VIEW, &matView );
}
HRESULT SetTexture (CTexture *pTexture)
{
HRESULT hResult = S_OK;
LPDIRECT3DTEXTURE2 pd3dt;
BOOL bTransparent;
if (pTexture != NULL)
{
pd3dt = pTexture->GetTexture ();
bTransparent = pTexture->IsTransparent ();
}
else
{
pd3dt = NULL;
bTransparent = FALSE;
}
if (pd3dt != g_pd3dtLast)
{
g_pd3dtLast = pd3dt;
hResult = g_pd3dDevice->SetTexture (0, pd3dt);
ASSERT (SUCCEEDED (hResult));
}
if (bTransparent != g_bTransparentLast)
{
g_bTransparentLast = bTransparent;
hResult = g_pd3dDevice->SetRenderState (D3DRENDERSTATE_COLORKEYENABLE, bTransparent);
ASSERT (SUCCEEDED (hResult));
}
return hResult;
}
extern "C" bool g3_draw_tmap (int cPoints, g3s_point **rgpPoints, g3s_uvl *rgpUvls, grs_bitmap *pbm)
{
ASSERT (cPoints <= sizeof (g_rgVerts) / sizeof (g_rgVerts[0]));
for (ULONG iPoint = 0; iPoint < cPoints; iPoint ++)
{
D3DLVERTEX *pvert = &g_rgVerts [iPoint];
const g3s_point *pPoint = rgpPoints [iPoint];
const g3s_uvl *pUvl = &rgpUvls [iPoint];
double dCol = f2fl (pUvl->l);
double dColR = min (1, max (0, dCol + g_fPSURed));
double dColG = min (1, max (0, dCol + g_fPSUGreen));
double dColB = min (1, max (0, dCol + g_fPSUBlue));
pvert->x = (D3DVALUE) f2fl (pPoint->p3_orig.x) / 10;
pvert->y = (D3DVALUE) f2fl (pPoint->p3_orig.y) / 10;
pvert->z = (D3DVALUE) f2fl (pPoint->p3_orig.z) / 10;
pvert->tu = (D3DVALUE) f2fl (pUvl->u);
pvert->tv = (D3DVALUE) f2fl (pUvl->v);
pvert->color = D3DRGBA (dColR, dColG, dColB, 0);
pvert->specular = 0;
}
HRESULT hResult;
hResult = SetTexture ((CTexture *) pbm->pvSurface);
ASSERT (SUCCEEDED (hResult));
hResult = g_pd3dDevice->DrawPrimitive (D3DPT_TRIANGLEFAN, D3DFVF_LVERTEX, g_rgVerts, cPoints, D3DDP_WAIT);
ASSERT (SUCCEEDED (hResult));
return hResult == S_OK;
}
extern "C" bool g3_draw_poly (int cPoints, g3s_point **rgpPoints)
{
ASSERT (cPoints <= sizeof (g_rgVerts) / sizeof (g_rgVerts[0]));
PALETTEENTRY pe = g_setTextures.ReadPalette (grd_curcanv->cv_color);
BYTE bR = pe.peRed;
BYTE bG = pe.peGreen;
BYTE bB = pe.peBlue;
double dColR = min (1, max (0, (float) bR / 256 + g_fPSURed));
double dColG = min (1, max (0, (float) bG / 256 + g_fPSUGreen));
double dColB = min (1, max (0, (float) bB / 256 + g_fPSUBlue));
for (ULONG iPoint = 0; iPoint < cPoints; iPoint ++)
{
D3DLVERTEX *pvert = &g_rgVerts [iPoint];
const g3s_point *pPoint = rgpPoints [iPoint];
pvert->x = (D3DVALUE) f2fl (pPoint->p3_orig.x) / 10;
pvert->y = (D3DVALUE) f2fl (pPoint->p3_orig.y) / 10;
pvert->z = (D3DVALUE) f2fl (pPoint->p3_orig.z) / 10;
pvert->tu = 0;
pvert->tv = 0;
pvert->color = D3DRGBA (dColR, dColG, dColB, 0);
pvert->specular = 0;
}
HRESULT hResult;
hResult = SetTexture (NULL);
ASSERT (SUCCEEDED (hResult));
hResult = g_pd3dDevice->DrawPrimitive (D3DPT_TRIANGLEFAN, D3DFVF_LVERTEX, g_rgVerts, cPoints, D3DDP_WAIT);
ASSERT (SUCCEEDED (hResult));
return S_OK;
}
extern "C" bool g3_draw_bitmap (vms_vector *pos, fix width, fix height,grs_bitmap *pbm)
{
ULONG cPoints = 4;
D3DVECTOR vecRight = g_vecRight * f2fl (width);
D3DVECTOR vecUp = g_vecUp * f2fl (height);
D3DVECTOR vecPos (
(D3DVALUE) f2fl (pos->x) / 10,
(D3DVALUE) f2fl (pos->y) / 10,
(D3DVALUE) f2fl (pos->z) / 10);
double dCol = 0.5;
double dColR = min (1, max (0, dCol + g_fPSURed));
double dColG = min (1, max (0, dCol + g_fPSUGreen));
double dColB = min (1, max (0, dCol + g_fPSUBlue));
D3DCOLOR col = D3DRGBA (dColR, dColG, dColB, 0);
D3DVALUE flAdjX, flAdjY;
CTexture *pTexture = (CTexture *) pbm->pvSurface;
pTexture->GetBitmapAdj (&flAdjX, &flAdjY);
D3DLVERTEX rgVerts [4] =
{
D3DLVERTEX (vecPos - vecRight - vecUp, col, 0, 0, flAdjY),
D3DLVERTEX (vecPos - vecRight + vecUp, col, 0, 0, 0),
D3DLVERTEX (vecPos + vecRight + vecUp, col, 0, flAdjX, 0),
D3DLVERTEX (vecPos + vecRight - vecUp, col, 0, flAdjX, flAdjY),
};
HRESULT hResult;
hResult = SetTexture (pTexture);
ASSERT (SUCCEEDED (hResult));
hResult = g_pd3dDevice->DrawPrimitive (D3DPT_TRIANGLEFAN, D3DFVF_LVERTEX, rgVerts, cPoints, D3DDP_WAIT);
ASSERT (SUCCEEDED (hResult));
return S_OK;
}
extern "C" void BlitToPrimary(HDC hSrcDC)
{
RECT rectDest;
rectDest.left = 0;
rectDest.top = 0;
rectDest.right = g_pFramework->m_dwRenderWidth;
rectDest.bottom = g_pFramework->m_dwRenderHeight;
if (g_bWindowed)
{
rectDest.left += g_pFramework->m_rcScreenRect.left;
rectDest.right += g_pFramework->m_rcScreenRect.left;
rectDest.top += g_pFramework->m_rcScreenRect.top;
rectDest.bottom += g_pFramework->m_rcScreenRect.top;
}
HDC hDstDC;
if (g_pFramework->GetFrontBuffer()->GetDC(&hDstDC) == DD_OK)
{
StretchBlt(hDstDC, rectDest.left, rectDest.top,
rectDest.right - rectDest.left, rectDest.bottom - rectDest.top,
hSrcDC, 0, 0, 320, 200, SRCCOPY);
g_pFramework->GetFrontBuffer()->ReleaseDC(hDstDC);
}
return;
}
extern "C" void BlitToPrimaryRect(HDC hSrcDC, int x, int y, int w, int h,
unsigned char *dst)
{
RECT rectDest;
int destWidth = g_pFramework->m_dwRenderWidth;
int destHeight = g_pFramework->m_dwRenderHeight;
rectDest.left = (x * destWidth) / 320;
rectDest.top = (y * destHeight) / 200;
rectDest.right = ((x + w) * destWidth) / 320;
rectDest.bottom = ((y + h) * destHeight) / 200;
if (g_bWindowed && (int)dst == BM_D3D_DISPLAY)
{
rectDest.left += g_pFramework->m_rcScreenRect.left;
rectDest.right += g_pFramework->m_rcScreenRect.left;
rectDest.top += g_pFramework->m_rcScreenRect.top;
rectDest.bottom += g_pFramework->m_rcScreenRect.top;
}
HDC hDstDC;
IDirectDrawSurface4 *pddsDest = ((int)dst == BM_D3D_DISPLAY) ?
g_pFramework->GetFrontBuffer() :
g_pFramework->GetRenderSurface();
if (pddsDest->GetDC(&hDstDC) == DD_OK)
{
StretchBlt(hDstDC, rectDest.left, rectDest.top,
rectDest.right - rectDest.left, rectDest.bottom - rectDest.top,
hSrcDC, x, y, w, h, SRCCOPY);
pddsDest->ReleaseDC(hDstDC);
}
return;
}
HRESULT Blit (
RECT &rectDest,
LPDIRECTDRAWSURFACE4 pddsSrc,
RECT &rectSrc,
DWORD dwFlags,
DDBLTFX *pddbltfx,
BOOL bPrimary)
{
rectDest.left = rectDest.left * g_pFramework->m_dwRenderWidth / 320;
rectDest.top = rectDest.top * g_pFramework->m_dwRenderHeight / 200;
rectDest.right = (rectDest.right + 1) * g_pFramework->m_dwRenderWidth / 320;
rectDest.bottom = (rectDest.bottom + 1) * g_pFramework->m_dwRenderHeight / 200;
if (g_bWindowed && bPrimary)
{
rectDest.left += g_pFramework->m_rcScreenRect.left;
rectDest.right += g_pFramework->m_rcScreenRect.left;
rectDest.top += g_pFramework->m_rcScreenRect.top;
rectDest.bottom += g_pFramework->m_rcScreenRect.top;
}
IDirectDrawSurface4 *pddsDest;
if (bPrimary)
{
pddsDest = g_pFramework->GetFrontBuffer ();
}
else
{
pddsDest = g_pFramework->GetRenderSurface();
}
return pddsDest->Blt (
&rectDest,
pddsSrc,
&rectSrc,
dwFlags,
pddbltfx);
}
static void findmask6(int in_mask, int *shift, int *bits6)
{
int i;
if (!in_mask) {
*shift = 0;
*bits6 = 6;
return;
}
i = 0;
while (!(in_mask & 1))
{
in_mask >>= 1;
i++;
}
*shift = i;
i = 0;
while (in_mask & 1)
{
in_mask >>= 1;
i++;
}
*bits6 = 6 - i;
}
void Win32_SetupColor(void)
{
DDPIXELFORMAT pf;
pf.dwSize = sizeof(pf);
g_pFramework->GetFrontBuffer ()->GetPixelFormat(&pf);
g_TrueColor = pf.dwRGBBitCount == 24 || pf.dwRGBBitCount == 32;
if (!g_TrueColor)
{
findmask6(pf.dwRBitMask, &g_RShift, &g_RBits6);
findmask6(pf.dwGBitMask, &g_GShift, &g_GBits6);
findmask6(pf.dwBBitMask, &g_BShift, &g_BBits6);
}
}
extern "C" void Win32_Rect (
int left, int top, int right, int bot,
int iSurf,
int iCol)
{
RECT rectDest = {left, top, right, bot};
DDBLTFX ddbltfx;
ddbltfx.dwSize = sizeof (ddbltfx);
#if 0
if (g_setTextures.HasPalette ())
{
ddbltfx.dwFillColor = iCol;
}
else
{
PALETTEENTRY pe = g_setTextures.ReadPalette (iCol);
ddbltfx.dwFillColor = *(DWORD*) &pe;
}
#else
unsigned char *p = gr_current_pal + iCol * 3;
if (g_TrueColor)
ddbltfx.dwFillColor = (255 << 24) | (p[0] << 18) |
(p[1] << 10) | (p[2] << 2);
else
ddbltfx.dwFillColor = (p[0] >> g_RBits6) << g_RShift |
(p[1] >> g_GBits6) << g_GShift |
(p[2] >> g_BBits6) << g_BShift;
#endif
HRESULT hr = Blit (
rectDest,
NULL,
rectDest,
DDBLT_WAIT | DDBLT_COLORFILL,
&ddbltfx,
iSurf == BM_D3D_DISPLAY);
}
extern "C" void Win32_BlitLinearToDirectX (
int w, int h,
int dx, int dy,
int sx, int sy,
void *pvSurface,
int iSurf,
BOOL bTransparent)
{
CTexture *pTexture = (CTexture *) pvSurface;
if (pTexture == NULL)
{
return;
}
if (!(w <= pTexture->m_ulWidthSource && h <= pTexture->m_ulHeightSource))
{
ASSERT (FALSE);
}
if (pTexture->isDirtyMemory ())
{
pTexture->CleanMemory ();
}
RECT rectDest = {dx, dy, dx + w, dy + h};
RECT rectSrc = {0, 0, w, h};
HRESULT hr = Blit (
rectDest,
pTexture->GetSurface (),
rectSrc,
DDBLT_WAIT,
NULL,
iSurf == BM_D3D_DISPLAY);
}
extern "C" void Win32_start_instance_matrix (vms_vector *pPos, vms_matrix *pOrient)
{
D3DMATRIX matOrientInv;
if (pOrient != NULL)
{
D3DMATRIX matOrient;
matOrient(0, 0) = (D3DVALUE) f2fl (pOrient->rvec.x);
matOrient(1, 0) = (D3DVALUE) f2fl (pOrient->rvec.y);
matOrient(2, 0) = (D3DVALUE) f2fl (pOrient->rvec.z);
matOrient(3, 0) = 0;
matOrient(0, 1) = (D3DVALUE) f2fl (pOrient->uvec.x);
matOrient(1, 1) = (D3DVALUE) f2fl (pOrient->uvec.y);
matOrient(2, 1) = (D3DVALUE) f2fl (pOrient->uvec.z);
matOrient(3, 1) = 0;
matOrient(0, 2) = (D3DVALUE) f2fl (pOrient->fvec.x);
matOrient(1, 2) = (D3DVALUE) f2fl (pOrient->fvec.y);
matOrient(2, 2) = (D3DVALUE) f2fl (pOrient->fvec.z);
matOrient(3, 2) = 0;
matOrient(0, 3) = 0;
matOrient(1, 3) = 0;
matOrient(2, 3) = 0;
matOrient(3, 3) = 1;
D3DMath_MatrixInvert (matOrientInv, matOrient);
}
else
{
D3DUtil_SetIdentityMatrix (matOrientInv);
}
D3DMATRIX matTranslate;
D3DUtil_SetTranslateMatrix (
matTranslate,
(D3DVALUE) f2fl (pPos->x) / 10,
(D3DVALUE) f2fl (pPos->y) / 10,
(D3DVALUE) f2fl (pPos->z) / 10);
D3DMATRIX matTmp;
D3DMath_MatrixMultiply (matTmp, g_stkWorlds.top (), matTranslate);
D3DMATRIX matWorld;
D3DMath_MatrixMultiply (matWorld, matTmp, matOrientInv);
g_stkWorlds.push (matWorld);
g_pd3dDevice->SetTransform( D3DTRANSFORMSTATE_WORLD, &matWorld );
}
extern "C" void Win32_done_instance (void)
{
g_stkWorlds.pop ();
D3DMATRIX matWorld = g_stkWorlds.top ();
g_pd3dDevice->SetTransform( D3DTRANSFORMSTATE_WORLD, &matWorld );
}
extern "C" void Win32_SetTextureBits (grs_bitmap *bm, unsigned char *data, int bRle)
{
CTexture *pTexture = (CTexture *) bm->pvSurface;
if (pTexture != NULL)
{
pTexture->SetBitmapData (data, bRle);
pTexture->SetTransparent (bm->bm_flags & BM_FLAG_TRANSPARENT);
}
}
extern "C" void Win32_CreateTexture (grs_bitmap *bm)
{
bm->pvSurface = (void *) g_setTextures.CreateTexture (
bm->bm_data,
bm->bm_w,
bm->bm_h,
bm->bm_rowsize);
}
extern "C" void Win32_FreeTexture (grs_bitmap *bm)
{
CTexture *pTexture = (CTexture *) bm->pvSurface;
if (pTexture != NULL)
{
g_setTextures.FreeTexture (pTexture);
bm->pvSurface = NULL;
}
}
extern "C" void Win32_SetTransparent (void *pvTexture, BOOL bTransparent)
{
CTexture *pTexture = (CTexture *) pvTexture;
if (pTexture != NULL)
{
pTexture->SetTransparent (bTransparent);
}
}

View file

@ -1,533 +0,0 @@
#include "pch.h"
#include "texture.h"
#include "d3dframe.h"
extern CD3DFramework* g_pFramework;
////////////////////////////////////////////////////////////////////////////
BOOL CTexture::s_bLocked = FALSE;
DDSURFACEDESC2 CTexture::s_ddsd;
HRESULT CTexture::Initialize (BYTE *rgbSource, ULONG ulWidth, ULONG ulHeight, ULONG ulPitch)
{
m_rgbSource = rgbSource;
m_ulWidthSource = ulWidth;
m_ulHeightSource = ulHeight;
m_ulPitchSource = ulPitch;
return S_OK;
}
HRESULT CTexture::Allocate (CPaletteInfo *ppi)
{
HRESULT hr;
ASSERT (m_spddsMemory == NULL);
if (ppi->IsPow2 ())
{
m_ulWidth = 1;
while (m_ulWidth < m_ulWidthSource)
m_ulWidth *= 2;
m_ulHeight = 1;
while (m_ulHeight < m_ulHeightSource)
m_ulHeight *= 2;
}
else
{
m_ulWidth = m_ulWidthSource;
m_ulHeight = m_ulHeightSource;
}
if (ppi->IsSquare ())
{
if (m_ulHeight > m_ulWidth)
{
m_ulWidth = m_ulHeight;
}
else
{
m_ulHeight = m_ulWidth;
}
}
m_flAdjX = (D3DVALUE) m_ulWidthSource / (D3DVALUE) m_ulWidth;
m_flAdjY = (D3DVALUE) m_ulHeightSource / (D3DVALUE) m_ulHeight;
DDSURFACEDESC2 ddsd;
ZeroMemory (&ddsd, sizeof (ddsd));
ddsd.dwSize = sizeof (ddsd);
ddsd.dwFlags = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT;
ddsd.dwWidth = m_ulWidth;
ddsd.dwHeight = m_ulHeight;
ddsd.ddsCaps.dwCaps = DDSCAPS_TEXTURE;
ddsd.ddsCaps.dwCaps2 = DDSCAPS2_TEXTUREMANAGE;
ppi->GetPixelFormat (&ddsd.ddpfPixelFormat);
hr = g_pFramework->GetDirectDraw ()->CreateSurface(&ddsd, &m_spddsMemory, NULL);
ASSERT (SUCCEEDED (hr));
if (FAILED (hr))
return hr;
ASSERT (m_spddsMemory != NULL);
m_spddtMemory = m_spddsMemory;
DirtyMemory ();
DDCOLORKEY ddck;
if (ppi->IsIndexed ())
{
ddck.dwColorSpaceLowValue = 255;
ddck.dwColorSpaceHighValue = 255;
}
else
{
ddck.dwColorSpaceLowValue = 0;
ddck.dwColorSpaceHighValue = 0;
}
hr = m_spddsMemory->SetColorKey (DDCKEY_SRCBLT, &ddck);
ASSERT (SUCCEEDED (hr));
if (ppi->GetPalette () != NULL)
{
hr = m_spddsMemory->SetPalette (ppi->GetPalette ());
ASSERT (SUCCEEDED (hr));
}
return hr;
}
HRESULT CTexture::Free (void)
{
HRESULT hr = S_OK;
m_spddtMemory = m_spddsMemory = NULL;
m_ulWidth = 0;
m_ulHeight = 0;
return hr;
}
HRESULT CTexture::Lock (void)
{
HRESULT hr;
if (!s_bLocked)
{
s_bLocked = TRUE;
s_ddsd.dwSize = sizeof (s_ddsd);
hr = m_spddsMemory->Lock (
NULL,
&s_ddsd,
#ifndef NDEBUG
DDLOCK_NOSYSLOCK |
#endif
DDLOCK_WAIT,
NULL);
ASSERT (SUCCEEDED (hr));
}
else
{
// already locked
hr = E_FAIL;
ASSERT (FALSE);
}
return hr;
}
HRESULT CTexture::Unlock (void)
{
HRESULT hr;
if (s_bLocked)
{
hr = m_spddsMemory->Unlock (NULL);
ASSERT (SUCCEEDED (hr));
s_bLocked = FALSE;
}
else
{
// not locked
hr = E_FAIL;
ASSERT (FALSE);
}
return hr;
}
void CTexture::PlotPixel (ULONG ulX, ULONG ulY, BYTE b)
{
ASSERT (ulX <= m_ulWidth);
ASSERT (ulY <= m_ulHeight);
ASSERT (s_bLocked);
ASSERT (s_ddsd.lpSurface != NULL);
switch (s_ddsd.ddpfPixelFormat.dwRGBBitCount)
{
case 8:
{
* (((LPBYTE) s_ddsd.lpSurface) + ulX + ulY * s_ddsd.lPitch) = b;
break;
}
case 16:
{
WORD w;
if (!(m_bTransparent && b == 255))
{
w = m_ppi->Read16 (b);
}
else
{
w = 0;
}
* (WORD *) (((LPBYTE) s_ddsd.lpSurface) + ulX * 2 + ulY * s_ddsd.lPitch) = w;
break;
}
default:
{
ASSERT (FALSE);
break;
}
}
}
void CTexture::SetBitmapData (BYTE *rgb, BOOL bRle)
{
m_rgbSource = rgb;
m_bRle = bRle;
DirtyMemory ();
}
void CTexture::CopyFromSource (void)
{
if (SUCCEEDED (Lock ()))
{
if (m_bRle)
{
PBYTE pbLine = m_rgbSource + m_ulHeightSource + 4;;
for (ULONG y = 0; y < m_ulHeightSource; y ++)
{
ULONG x = 0;
PBYTE pbSrc = pbLine;
while (1)
{
const BYTE RLE_CODE = 0xE0;
BYTE b = *pbSrc++;
if ((b & RLE_CODE) != RLE_CODE)
{
PlotPixel (x++, y, b);
}
else
{
BYTE cb = b & (~RLE_CODE);
if (cb == 0)
break;
b = *pbSrc++;
while (cb--)
PlotPixel (x++, y, b);
}
}
ASSERT (x <= m_ulWidthSource);
pbLine += m_rgbSource [y + 4];
}
}
else
{
LPBYTE lpbDest = (LPBYTE) s_ddsd.lpSurface;
LPBYTE lpbSrc = m_rgbSource;
switch (s_ddsd.ddpfPixelFormat.dwRGBBitCount)
{
case 8:
{
for (ULONG y = m_ulHeightSource; y != 0; y--)
{
memcpy (lpbDest, lpbSrc, m_ulPitchSource);
lpbDest += s_ddsd.lPitch;
lpbSrc += m_ulPitchSource;
}
break;
}
case 16:
{
for (ULONG y = m_ulHeightSource; y != 0; y--)
{
LPBYTE lpbLineSrc = lpbSrc;
LPWORD lpwLineDest = (LPWORD) lpbDest;
if (m_bTransparent)
{
for (ULONG x = m_ulWidthSource; x != 0; x--)
{
BYTE b = *lpbLineSrc++;
*lpwLineDest++ = (b == 255) ? 0 : m_ppi->Read16 (b);
}
}
else
{
for (ULONG x = m_ulWidthSource; x != 0; x--)
{
*lpwLineDest++ = m_ppi->Read16 (*lpbLineSrc++);
}
}
lpbDest += s_ddsd.lPitch;
lpbSrc += m_ulPitchSource;
}
break;
}
default:
{
ASSERT (FALSE);
break;
}
}
}
Unlock ();
}
else
{
ASSERT (FALSE);
}
}
HRESULT CTexture::CleanMemory (void)
{
CopyFromSource ();
m_bDirtyMemory = FALSE;
return S_OK;
}
IDirect3DTexture2 *CTexture::GetTexture ()
{
if (m_bDirtyMemory)
{
CleanMemory ();
}
return m_spddtMemory;
}
////////////////////////////////////////////////////////////////////////////
struct FindTextureData
{
DWORD bpp; // we want a texture format of this bpp
DDPIXELFORMAT ddpf; // place the format here
};
HRESULT CALLBACK FindTextureCallback(LPDDPIXELFORMAT pddpf, LPVOID lParam)
{
FindTextureData * FindData = (FindTextureData *)lParam;
//
// we use GetDC/BitBlt to init textures so we only
// want to use formats that GetDC will support.
//
if (pddpf->dwFlags & (DDPF_ALPHA|DDPF_ALPHAPIXELS))
return DDENUMRET_OK;
/*
if (pddpf->dwRGBBitCount == 16)
{
FindData->ddpf = ddpf;
}
return DDENUMRET_OK;
*/
// if (!(pddpf->dwFlags & DDPF_ALPHAPIXELS))
// return DDENUMRET_OK;
if (pddpf->dwRGBBitCount < 8)
return DDENUMRET_OK;
if (pddpf->dwRGBBitCount == 8 && !(pddpf->dwFlags & DDPF_PALETTEINDEXED8))
return DDENUMRET_OK;
if (pddpf->dwRGBBitCount > 8 && !(pddpf->dwFlags & DDPF_RGB))
return DDENUMRET_OK;
//
// keep the texture format that is nearest to the bitmap we have
//
if (FindData->ddpf.dwRGBBitCount == 0 ||
(pddpf->dwRGBBitCount >= FindData->bpp && pddpf->dwRGBBitCount <= FindData->ddpf.dwRGBBitCount) //&&
//(pddpf->dwAlphaBitDepth != 0 && pddpf->dwAlphaBitDepth > FindData->ddpf.dwAlphaBitDepth) // ALPHA BIT DEPTHS ARE REVERSED!!!!
)
{
FindData->ddpf = *pddpf;
}
return DDENUMRET_OK;
}
void ChooseTextureFormat(LPDIRECT3DDEVICE3 Device, DWORD bpp, DDPIXELFORMAT *pddpf)
{
HRESULT hr;
FindTextureData FindData;
ZeroMemory(&FindData, sizeof(FindData));
FindData.bpp = bpp;
hr = Device->EnumTextureFormats(FindTextureCallback, (LPVOID)&FindData);
ASSERT(hr == S_OK);
*pddpf = FindData.ddpf;
}
HRESULT CPaletteInfo::Initialize ()
{
m_spddpPalette = NULL;
//
// find the best texture format to use.
//
ChooseTextureFormat (g_pFramework->GetD3DDevice (), 8, &m_ddpfPixelFormat);
m_cshftR = GetShift (m_mskR = m_ddpfPixelFormat.dwRBitMask);
m_cshftG = GetShift (m_mskG = m_ddpfPixelFormat.dwGBitMask);
m_cshftB = GetShift (m_mskB = m_ddpfPixelFormat.dwBBitMask);
HRESULT hr;
D3DDEVICEDESC descHAL, descHEL;
descHAL.dwSize = descHEL.dwSize = sizeof (descHAL);
hr = g_pFramework->GetD3DDevice ()->GetCaps (&descHAL, &descHEL);
ASSERT (SUCCEEDED (hr));
if (!descHAL.dwFlags) {
m_bPow2 = (descHEL.dpcTriCaps.dwTextureCaps & D3DPTEXTURECAPS_POW2) != 0;
m_bSquare = (descHEL.dpcTriCaps.dwTextureCaps & D3DPTEXTURECAPS_SQUAREONLY) != 0;
} else {
m_bPow2 = (descHAL.dpcTriCaps.dwTextureCaps & D3DPTEXTURECAPS_POW2) != 0;
m_bSquare = (descHAL.dpcTriCaps.dwTextureCaps & D3DPTEXTURECAPS_SQUAREONLY) != 0;
}
if (IsIndexed ())
{
hr = g_pFramework->GetDirectDraw ()->CreatePalette (DDPCAPS_8BIT | DDPCAPS_ALLOW256, m_rgpe, &m_spddpPalette, NULL);
ASSERT (SUCCEEDED (hr));
}
return S_OK;
}
HRESULT CPaletteInfo::Uninitialize ()
{
m_spddpPalette = NULL; // smart pointer release
return S_OK;
}
void CPaletteInfo::SetPaletteEntries (PALETTEENTRY rgpe [256])
{
// okay, we don't really need to cache the palette values
// we could implement ReadPalette by individual Getentries calls...
memcpy (m_rgpe, rgpe, sizeof (m_rgpe));
if (m_spddpPalette != NULL)
{
HRESULT hr = m_spddpPalette->SetEntries (0, 0, 256, m_rgpe);
ASSERT (SUCCEEDED (hr));
}
}
void CPaletteInfo::GetPaletteEntries (PALETTEENTRY rgpe [256])
{
if (m_spddpPalette != NULL)
{
HRESULT hr = m_spddpPalette->GetEntries (0, 0, 256, m_rgpe);
ASSERT (SUCCEEDED (hr));
}
}
////////////////////////////////////////////////////////////////
CPaletteInfo *CTexture::m_ppi;
HRESULT CTextureSet::Initialize ()
{
HRESULT hr;
hr = m_pi.Initialize ();
ASSERT (SUCCEEDED (hr));
CTexture::m_ppi = &m_pi;
for (TEXTURE_SET::iterator iter = m_setTextures.begin ();
iter != m_setTextures.end ();
iter ++)
{
(*iter)->Allocate (&m_pi);
}
return hr;
}
HRESULT CTextureSet::Uninitialize ()
{
for (TEXTURE_SET::iterator iter = m_setTextures.begin ();
iter != m_setTextures.end ();
iter ++)
{
(*iter)->Free ();
}
m_pi.Uninitialize ();
return S_OK;
}
CTexture *CTextureSet::CreateTexture (BYTE *rgbSource, ULONG dx, ULONG dy, ULONG ulPitch)
{
CTexture *pTexture = new CTexture;
pTexture->Initialize (rgbSource, dx, dy, ulPitch);
pTexture->Allocate (&m_pi);
m_setTextures.insert (pTexture);
return pTexture;
}
void CTextureSet::FreeTexture (CTexture *pTexture)
{
m_setTextures.erase (pTexture);
delete pTexture;
}
void CTextureSet::DirtyTextures (void)
{
for (TEXTURE_SET::iterator iter = m_setTextures.begin ();
iter != m_setTextures.end ();
iter ++)
{
(*iter)->DirtyMemory ();
}
}
void CTextureSet::SetPaletteEntries (PALETTEENTRY rgpe [256])
{
m_pi.SetPaletteEntries (rgpe);
if (!m_pi.IsIndexed ())
{
DirtyTextures ();
}
}
void CTextureSet::GetPaletteEntries (PALETTEENTRY rgpe [256])
{
m_pi.GetPaletteEntries (rgpe);
}

View file

@ -1,71 +0,0 @@
/*
THE COMPUTER CODE CONTAINED HEREIN IS THE SOLE PROPERTY OF PARALLAX
SOFTWARE CORPORATION ("PARALLAX"). PARALLAX, IN DISTRIBUTING THE CODE TO
END-USERS, AND SUBJECT TO ALL OF THE TERMS AND CONDITIONS HEREIN, GRANTS A
ROYALTY-FREE, PERPETUAL LICENSE TO SUCH END-USERS FOR USE BY SUCH END-USERS
IN USING, DISPLAYING, AND CREATING DERIVATIVE WORKS THEREOF, SO LONG AS
SUCH USE, DISPLAY OR CREATION IS FOR NON-COMMERCIAL, ROYALTY OR REVENUE
FREE PURPOSES. IN NO EVENT SHALL THE END-USER USE THE COMPUTER CODE
CONTAINED HEREIN FOR REVENUE-BEARING PURPOSES. THE END-USER UNDERSTANDS
AND AGREES TO THE TERMS HEREIN AND ACCEPTS THE SAME BY USE OF THIS FILE.
COPYRIGHT 1993-1998 PARALLAX SOFTWARE CORPORATION. ALL RIGHTS RESERVED.
*/
// File nearly completely rewritten by dph-man
#include <windows.h>
#include <mmsystem.h> // DPH: We use timeGetTime from here...
#include "types.h"
#include "maths.h"
#include "timer.h"
static int Installed = 0;
static unsigned long old_tv;
fix timer_get_fixed_seconds()
{
fix x;
//Ye good olde unix:
//Ye bad olde Windows DPH:-)
/* DPH: Using timeGetTime will fail approximately 47 days after Windows was
started as the timer wraps around to 0. Ever had Windows not crash for 47
consecutive days? Thought not. */
unsigned long tv_now=timeGetTime()-old_tv;
x=i2f(tv_now/1000) | fixdiv(i2f(tv_now % 1000),i2f(1000));
return x;
}
void delay(int d_time)
{
fix t, total;
total = (F1_0 * d_time) / 1000;
t = timer_get_fixed_seconds();
while (timer_get_fixed_seconds() - t < total) ;
}
void timer_close()
{
Installed = 0;
}
void timer_init()
{
if (Installed)
return;
Installed = 1;
/* DPH: Using timeGetTime will fail approximately 47 days after Windows was
started as the timer wraps around to 0. Ever had Windows not crash for 47
consecutive days? Thought not. */
old_tv=timeGetTime();
}
// NOTE: This C file has been "neutered" by dph-man. If someone wants to work
// on this, feel free. I don't use joystick :-)

View file

@ -1,690 +0,0 @@
//-----------------------------------------------------------------------------
// File: WinMain.cpp
//
// Desc: Windows code for Direct3D samples
//
// This code uses the Direct3D sample framework.
//
//
// Copyright (c) 1996-1998 Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#include "pch.h"
#include "WinMain.h"
#include "D3DFrame.h"
#include "D3DEnum.h"
#include "D3DUtil.h"
#include "resource.h"
#include "scene.h"
//-----------------------------------------------------------------------------
// Global variables for using the D3D sample framework class
//-----------------------------------------------------------------------------
CD3DFramework* g_pFramework = NULL;
BOOL g_bActive = FALSE;
BOOL g_bReady = FALSE;
BOOL g_bFrameMoving = TRUE;
BOOL g_bSingleStep = FALSE;
BOOL g_bWindowed = TRUE;
BOOL g_bShowStats = TRUE;
RECT g_rcWindow;
HACCEL g_hAccel;
HWND g_hWnd;
enum APPMSGTYPE { MSG_NONE, MSGERR_APPMUSTEXIT, MSGWARN_SWITCHTOSOFTWARE };
//-----------------------------------------------------------------------------
// Local function-prototypes
//-----------------------------------------------------------------------------
INT CALLBACK AboutProc( HWND, UINT, WPARAM, LPARAM );
LRESULT CALLBACK WndProc( HWND, UINT, WPARAM, LPARAM );
HRESULT Initialize3DEnvironment( HWND );
HRESULT Change3DEnvironment( HWND );
HRESULT Render3DEnvironment();
VOID Cleanup3DEnvironment();
VOID DisplayFrameworkError( HRESULT, APPMSGTYPE );
VOID AppShowStats();
VOID AppOutputText( LPDIRECT3DDEVICE3, DWORD, DWORD, CHAR* );
VOID AppPause( BOOL );
//-----------------------------------------------------------------------------
// 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 strCmdLine, INT )
extern "C" INT InitMain ()
{
HINSTANCE hInst = GetModuleHandle (NULL);
// Register the window class
WNDCLASS wndClass = { CS_HREDRAW | CS_VREDRAW, WndProc, 0, 0, hInst,
LoadIcon( hInst, MAKEINTRESOURCE(IDI_MAIN_ICON)),
LoadCursor(NULL, IDC_ARROW),
(HBRUSH)GetStockObject(WHITE_BRUSH),
MAKEINTRESOURCE(IDR_MENU),
TEXT("Render Window") };
RegisterClass( &wndClass );
// Create our main window
g_hWnd = CreateWindow( TEXT("Render Window"), g_strAppTitle,
WS_OVERLAPPEDWINDOW, CW_USEDEFAULT,
CW_USEDEFAULT, 300, 300, 0L, 0L, hInst, 0L );
RECT rect;
if (GetClientRect (g_hWnd, &rect))
{
int cx = 320 + (300 - rect.right);
int cy = 200 + (300 - rect.bottom);
SetWindowPos (g_hWnd, NULL, 0, 0, cx, cy, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOREDRAW | SWP_NOZORDER);
}
ShowWindow( g_hWnd, SW_SHOWNORMAL );
UpdateWindow( g_hWnd );
// Save the window size/pos for switching modes
GetWindowRect( g_hWnd, &g_rcWindow );
// Load keyboard accelerators
g_hAccel = LoadAccelerators( hInst, MAKEINTRESOURCE(IDR_MAIN_ACCEL) );
// Enumerate available D3D devices, passing a callback that allows devices
// to be accepted/rejected based on what capabilities the app requires.
HRESULT hr;
if( FAILED( hr = D3DEnum_EnumerateDevices( App_ConfirmDevice ) ) )
{
DisplayFrameworkError( hr, MSGERR_APPMUSTEXIT );
return 0;
}
// Check if we could not get a device that renders into a window, which
// means the display must be 16- or 256-color mode. If so, let's bail.
D3DEnum_DriverInfo* pDriverInfo;
D3DEnum_DeviceInfo* pDeviceInfo;
D3DEnum_GetSelectedDriver( &pDriverInfo, &pDeviceInfo );
if( FALSE == pDeviceInfo->bWindowed )
{
Cleanup3DEnvironment();
DisplayFrameworkError( D3DFWERR_INVALIDMODE, MSGERR_APPMUSTEXIT );
return 0;
}
// Initialize the 3D environment for the app
if( FAILED( hr = Initialize3DEnvironment( g_hWnd ) ) )
{
Cleanup3DEnvironment();
DisplayFrameworkError( hr, MSGERR_APPMUSTEXIT );
return 0;
}
g_bReady = TRUE;
return 1;
}
void PumpMessages (void)
{
MSG msg;
while (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
{
// Exit App ?!?
if (msg.message == WM_QUIT)
{
return;
}
if (!TranslateAccelerator (g_hWnd, g_hAccel, &msg))
{
TranslateMessage (&msg);
DispatchMessage (&msg);
}
}
}
//-----------------------------------------------------------------------------
// Name: WndProc()
// Desc: This is the basic Windows-programming function that processes
// Windows messages. We need to handle window movement, painting,
// and destruction.
//-----------------------------------------------------------------------------
LRESULT CALLBACK WndProc( HWND g_hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam )
{
switch( uMsg )
{
case WM_PAINT:
if( g_pFramework )
{
// If we are paused, and in fullscreen mode, give the dialogs
// a GDI surface to draw on.
if( !g_bReady && !g_bWindowed)
g_pFramework->FlipToGDISurface( TRUE );
else // Simply repaint the frame's contents
g_pFramework->ShowFrame();
}
break;
case WM_MOVE:
if( g_bActive && g_bReady && g_bWindowed )
{
GetWindowRect( g_hWnd, &g_rcWindow );
g_pFramework->Move( (SHORT)LOWORD(lParam), (SHORT)HIWORD(lParam) );
}
break;
case WM_SIZE:
// Check to see if we are losing our window...
if( SIZE_MAXHIDE==wParam || SIZE_MINIMIZED==wParam )
g_bActive = FALSE;
else g_bActive = TRUE;
// A new window size will require a new viewport and backbuffer
// size, so the 3D structures must be changed accordingly.
if( g_bActive && g_bReady && g_bWindowed )
{
g_bReady = FALSE;
GetWindowRect( g_hWnd, &g_rcWindow );
Change3DEnvironment( g_hWnd );
g_bReady = TRUE;
}
break;
case WM_GETMINMAXINFO:
((MINMAXINFO*)lParam)->ptMinTrackSize.x = 100;
((MINMAXINFO*)lParam)->ptMinTrackSize.y = 100;
break;
case WM_SETCURSOR:
if( g_bActive && g_bReady && (!g_bWindowed) )
{
SetCursor(NULL);
return TRUE;
}
break;
case WM_CLOSE:
DestroyWindow( g_hWnd );
return 0;
case WM_DESTROY:
Cleanup3DEnvironment();
PostQuitMessage(0);
return 0L;
case WM_ENTERMENULOOP:
AppPause(TRUE);
break;
case WM_EXITMENULOOP:
AppPause(FALSE);
break;
case WM_CONTEXTMENU:
{
HMENU hMenu = LoadMenu( 0, MAKEINTRESOURCE(IDR_POPUP) );
TrackPopupMenuEx( GetSubMenu( hMenu, 0 ),
TPM_VERTICAL, LOWORD(lParam),
HIWORD(lParam), g_hWnd, NULL );
}
break;
case WM_COMMAND:
switch( LOWORD(wParam) )
{
case SC_MONITORPOWER:
// Prevent potential crashes when the monitor powers down
return 1;
case IDM_TOGGLESTART:
g_bFrameMoving = !g_bFrameMoving;
break;
case IDM_SINGLESTEP:
g_bSingleStep = TRUE;
break;
case IDM_CHANGEDEVICE:
// Display the driver-selection dialog box.
if( g_bActive && g_bReady )
{
AppPause(TRUE);
if( g_bWindowed )
GetWindowRect( g_hWnd, &g_rcWindow );
HWND hWnd = g_hWnd;
if( IDOK == D3DEnum_UserDlgSelectDriver( hWnd, g_bWindowed ) )
{
D3DEnum_DriverInfo* pDriverInfo;
D3DEnum_DeviceInfo* pDeviceInfo;
D3DEnum_GetSelectedDriver( &pDriverInfo, &pDeviceInfo );
g_bWindowed = pDeviceInfo->bWindowed;
Change3DEnvironment( g_hWnd );
}
AppPause(FALSE);
}
return 0;
case IDM_TOGGLEFULLSCREEN:
// Toggle the fullscreen/window mode
if( g_bActive && g_bReady )
{
g_bReady = FALSE;
if( g_bWindowed )
GetWindowRect( g_hWnd, &g_rcWindow );
g_bWindowed = !g_bWindowed;
Change3DEnvironment( g_hWnd );
g_bReady = TRUE;
}
return 0;
case IDM_HELP:
AppPause(TRUE);
DialogBox( (HINSTANCE)GetWindowLong( g_hWnd, GWL_HINSTANCE ),
MAKEINTRESOURCE(IDD_ABOUT), g_hWnd, (DLGPROC)AboutProc );
AppPause(FALSE);
return 0;
case IDM_EXIT:
// Recieved key/menu command to exit app
SendMessage( g_hWnd, WM_CLOSE, 0, 0 );
return 0;
}
break;
}
return DefWindowProc( g_hWnd, uMsg, wParam, lParam );
}
//-----------------------------------------------------------------------------
// Name: AboutProc()
// Desc: Minimal message proc function for the about box
//-----------------------------------------------------------------------------
BOOL CALLBACK AboutProc( HWND g_hWnd, UINT uMsg, WPARAM wParam, LPARAM )
{
if( WM_COMMAND == uMsg )
if( IDOK == LOWORD(wParam) || IDCANCEL == LOWORD(wParam) )
EndDialog (g_hWnd, TRUE);
return ( WM_INITDIALOG == uMsg ) ? TRUE : FALSE;
}
//-----------------------------------------------------------------------------
// Note: From this point on, the code is DirectX specific support for the app.
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Name: AppInitialize()
// Desc: Initializes the sample framework, then calls the app-specific function
// to initialize device specific objects. This code is structured to
// handled any errors that may occur duing initialization
//-----------------------------------------------------------------------------
HRESULT AppInitialize( HWND g_hWnd )
{
D3DEnum_DriverInfo* pDriverInfo;
D3DEnum_DeviceInfo* pDeviceInfo;
DWORD dwFrameworkFlags = 0L;
HRESULT hr;
D3DEnum_GetSelectedDriver( &pDriverInfo, &pDeviceInfo );
dwFrameworkFlags |= (!g_bWindowed ? D3DFW_FULLSCREEN : 0L );
dwFrameworkFlags |= ( g_bAppUseZBuffer ? D3DFW_ZBUFFER : 0L );
dwFrameworkFlags |= ( g_bAppUseBackBuffer ? D3DFW_BACKBUFFER : 0L );
// Initialize the D3D framework
if( SUCCEEDED( hr = g_pFramework->Initialize( g_hWnd, &pDriverInfo->guid,
&pDeviceInfo->guid, &pDeviceInfo->pCurrentMode->ddsd,
dwFrameworkFlags ) ) )
{
// Let the app run its startup code which creates the 3d scene.
if( SUCCEEDED( hr = App_InitDeviceObjects( g_pFramework->GetD3DDevice(),
g_pFramework->GetViewport() ) ) )
return S_OK;
else
{
App_DeleteDeviceObjects( g_pFramework->GetD3DDevice(),
g_pFramework->GetViewport() );
g_pFramework->DestroyObjects();
}
}
// If we get here, the first initialization passed failed. If that was with a
// hardware device, try again using a software rasterizer instead.
if( pDeviceInfo->bIsHardware )
{
// Try again with a software rasterizer
DisplayFrameworkError( hr, MSGWARN_SWITCHTOSOFTWARE );
D3DEnum_SelectDefaultDriver( D3DENUM_SOFTWAREONLY );
return AppInitialize( g_hWnd );
}
return hr;
}
//-----------------------------------------------------------------------------
// Name: Initialize3DEnvironment()
// Desc: Called when the app window is initially created, this triggers
// creation of the remaining portion (the 3D stuff) of the app.
//-----------------------------------------------------------------------------
HRESULT Initialize3DEnvironment( HWND g_hWnd )
{
HRESULT hr;
// Initialize the app
if( FAILED( hr = App_OneTimeSceneInit( g_hWnd ) ) )
return E_FAIL;
// Create a new CD3DFramework class. This class does all of our D3D
// initialization and manages the common D3D objects.
if( NULL == ( g_pFramework = new CD3DFramework() ) )
return E_OUTOFMEMORY;
// Finally, initialize the framework and scene.
return AppInitialize( g_hWnd );
}
//-----------------------------------------------------------------------------
// Name: Change3DEnvironment()
// Desc: Handles driver, device, and/or mode changes for the app.
//-----------------------------------------------------------------------------
HRESULT Change3DEnvironment( HWND g_hWnd )
{
HRESULT hr;
// Release all objects that need to be re-created for the new device
App_DeleteDeviceObjects( g_pFramework->GetD3DDevice(),
g_pFramework->GetViewport() );
// Release the current framework objects (they will be recreated later on)
if( FAILED( hr = g_pFramework->DestroyObjects() ) )
{
DisplayFrameworkError( hr, MSGERR_APPMUSTEXIT );
DestroyWindow( g_hWnd );
return hr;
}
// In case we're coming from a fullscreen mode, restore the window size
if( g_bWindowed )
{
SetWindowPos( g_hWnd, HWND_NOTOPMOST, g_rcWindow.left, g_rcWindow.top,
( g_rcWindow.right - g_rcWindow.left ),
( g_rcWindow.bottom - g_rcWindow.top ), SWP_SHOWWINDOW );
}
// Inform the framework class of the driver change. It will internally
// re-create valid surfaces, a d3ddevice, and a viewport.
if( FAILED( hr = AppInitialize( g_hWnd ) ) )
{
DisplayFrameworkError( hr, MSGERR_APPMUSTEXIT );
DestroyWindow( g_hWnd );
return hr;
}
// Trigger the rendering of a frame and return
g_bSingleStep = TRUE;
return S_OK;
}
FLOAT g_fTime;
extern "C" HRESULT Win32_start_frame ()
{
// Check the cooperative level before rendering
if( FAILED( g_pFramework->GetDirectDraw()->TestCooperativeLevel() ) )
return S_OK;
// Get the current time
g_fTime = GetTickCount() * 0.001f;
return App_StartFrame( g_pFramework->GetD3DDevice(),
g_pFramework->GetViewport(),
(D3DRECT*)g_pFramework->GetViewportRect() );
}
extern "C" HRESULT Win32_end_frame ()
{
// Show the frame rate, etc.
if( g_bShowStats )
AppShowStats();
return App_EndFrame ();
}
extern "C" HRESULT Win32_flip_screens ()
{
// Show the frame on the primary surface.
if( DDERR_SURFACELOST == g_pFramework->ShowFrame() )
{
g_pFramework->RestoreSurfaces();
App_RestoreSurfaces();
}
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: Cleanup3DEnvironment()
// Desc: Cleanup scene objects
//-----------------------------------------------------------------------------
VOID Cleanup3DEnvironment()
{
if( g_pFramework )
{
App_FinalCleanup( g_pFramework->GetD3DDevice(),
g_pFramework->GetViewport() );
SAFE_DELETE( g_pFramework );
}
g_bActive = FALSE;
g_bReady = FALSE;
}
//-----------------------------------------------------------------------------
// Name: AppPause()
// Desc: Called in to toggle the pause state of the app. This function
// brings the GDI surface to the front of the display, so drawing
// output like message boxes and menus may be displayed.
//-----------------------------------------------------------------------------
VOID AppPause( BOOL bPause )
{
static DWORD dwAppPausedCount = 0L;
if( bPause && 0 == dwAppPausedCount )
if( g_pFramework )
g_pFramework->FlipToGDISurface( TRUE );
dwAppPausedCount += ( bPause ? +1 : -1 );
g_bReady = (0==dwAppPausedCount);
}
//-----------------------------------------------------------------------------
// Name: AppShowStats()
// Desc: Shows frame rate and dimensions of the rendering device. Note: a
// "real" app wouldn't query the surface dimensions each frame.
//-----------------------------------------------------------------------------
VOID AppShowStats()
{
static FLOAT fFPS = 0.0f;
static FLOAT fLastTime = 0.0f;
static DWORD dwFrames = 0L;
// Keep track of the time lapse and frame count
FLOAT fTime = GetTickCount() * 0.001f; // Get current time in seconds
++dwFrames;
// Update the frame rate once per second
if( fTime - fLastTime > 1.0f )
{
fFPS = dwFrames / (fTime - fLastTime);
fLastTime = fTime;
dwFrames = 0L;
}
// Get dimensions of the render surface
DDSURFACEDESC2 ddsd;
ddsd.dwSize = sizeof(DDSURFACEDESC2);
g_pFramework->GetRenderSurface()->GetSurfaceDesc(&ddsd);
// Setup the text buffer to write out
CHAR buffer[80];
sprintf( buffer, "%7.02f fps (%dx%dx%d)", fFPS, ddsd.dwWidth,
ddsd.dwHeight, ddsd.ddpfPixelFormat.dwRGBBitCount );
AppOutputText( g_pFramework->GetD3DDevice(), 0, 0, buffer );
}
//-----------------------------------------------------------------------------
// Name: AppOutputText()
// Desc: Draws text on the window.
//-----------------------------------------------------------------------------
VOID AppOutputText( LPDIRECT3DDEVICE3 pd3dDevice, DWORD x, DWORD y, CHAR* str )
{
LPDIRECTDRAWSURFACE4 pddsRenderSurface;
if( FAILED( pd3dDevice->GetRenderTarget( &pddsRenderSurface ) ) )
return;
// Get a DC for the surface. Then, write out the buffer
HDC hDC;
if( SUCCEEDED( pddsRenderSurface->GetDC(&hDC) ) )
{
SetTextColor( hDC, RGB(255,255,0) );
SetBkMode( hDC, TRANSPARENT );
ExtTextOut( hDC, x, y, 0, NULL, str, strlen(str), NULL );
pddsRenderSurface->ReleaseDC(hDC);
}
pddsRenderSurface->Release();
}
//-----------------------------------------------------------------------------
// Name: DisplayFrameworkError()
// Desc: Displays error messages in a message box
//-----------------------------------------------------------------------------
VOID DisplayFrameworkError( HRESULT hr, APPMSGTYPE errType )
{
CHAR strMsg[512];
switch( hr )
{
case D3DENUMERR_NOCOMPATIBLEDEVICES:
strcpy( strMsg, TEXT("Could not find any compatible Direct3D\n"
"devices.") );
break;
case D3DENUMERR_SUGGESTREFRAST:
strcpy( strMsg, TEXT("Could not find any compatible devices.\n\n"
"Try enabling the reference rasterizer using\n"
"EnableRefRast.reg.") );
break;
case D3DENUMERR_ENUMERATIONFAILED:
strcpy( strMsg, TEXT("Enumeration failed. Your system may be in an\n"
"unstable state and need to be rebooted") );
break;
case D3DFWERR_INITIALIZATIONFAILED:
strcpy( strMsg, TEXT("Generic initialization error.\n\nEnable "
"debug output for detailed information.") );
break;
case D3DFWERR_NODIRECTDRAW:
strcpy( strMsg, TEXT("No DirectDraw") );
break;
case D3DFWERR_NODIRECT3D:
strcpy( strMsg, TEXT("No Direct3D") );
break;
case D3DFWERR_INVALIDMODE:
strcpy( strMsg, TEXT("This sample requires a 16-bit (or higher) "
"display mode\nto run in a window.\n\nPlease switch "
"your desktop settings accordingly.") );
break;
case D3DFWERR_COULDNTSETCOOPLEVEL:
strcpy( strMsg, TEXT("Could not set Cooperative Level") );
break;
case D3DFWERR_NO3DDEVICE:
strcpy( strMsg, TEXT("No 3D Device") );
break;
case D3DFWERR_NOZBUFFER:
strcpy( strMsg, TEXT("No ZBuffer") );
break;
case D3DFWERR_NOVIEWPORT:
strcpy( strMsg, TEXT("No Viewport") );
break;
case D3DFWERR_NOPRIMARY:
strcpy( strMsg, TEXT("No primary") );
break;
case D3DFWERR_NOCLIPPER:
strcpy( strMsg, TEXT("No Clipper") );
break;
case D3DFWERR_BADDISPLAYMODE:
strcpy( strMsg, TEXT("Bad display mode") );
break;
case D3DFWERR_NOBACKBUFFER:
strcpy( strMsg, TEXT("No backbuffer") );
break;
case D3DFWERR_NONZEROREFCOUNT:
strcpy( strMsg, TEXT("Nonzerorefcount") );
break;
case D3DFWERR_NORENDERTARGET:
strcpy( strMsg, TEXT("No render target") );
break;
case E_OUTOFMEMORY:
strcpy( strMsg, TEXT("Not enough memory!") );
break;
case DDERR_OUTOFVIDEOMEMORY:
strcpy( strMsg, TEXT("There was insufficient video memory "
"to use the\nhardware device.") );
break;
default:
strcpy( strMsg, TEXT("Generic application error.\n\nEnable "
"debug output for detailed information.") );
}
if( MSGERR_APPMUSTEXIT == errType )
{
strcat( strMsg, TEXT("\n\nThis sample will now exit.") );
MessageBox( NULL, strMsg, g_strAppTitle, MB_ICONERROR|MB_OK );
}
else
{
if( MSGWARN_SWITCHTOSOFTWARE == errType )
strcat( strMsg, TEXT("\n\nSwitching to software rasterizer.") );
MessageBox( NULL, strMsg, g_strAppTitle, MB_ICONWARNING|MB_OK );
}
}

View file

@ -1560,12 +1560,10 @@ void controls_read_all()
if (CONTROL_USING_MOUSE) {
//--------- Read Mouse -----------
mouse_get_delta( &dx, &dy, &dz );
mouse_axis[0] = (dx*60); //(dx*FrameTime)/35;
mouse_axis[1] = (dy*85); //(dy*FrameTime)/25;
mouse_axis[2] = (dz*512);
mouse_axis[0] = (dx*FrameTime)/35;
mouse_axis[1] = (dy*FrameTime)/25;
mouse_axis[2] = (dz*FrameTime)/25;
mouse_buttons = mouse_get_btns();
//mprintf(( 0, "Mouse %d,%d b:%d, 0x%x\n", mouse_axis[0], mouse_axis[1], mouse_buttons, FrameTime ));
use_mouse=1;
} else {
mouse_axis[0] = 0;