aboutsummaryrefslogtreecommitdiffstats
path: root/demos/natives/wgl.c
blob: 15119e88b1698e9f4184f6be196e162cb1714f7b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
/*****************************************************************

  Xmame OpenGL driver

  Written based on the x11 driver by Mike Oliphant - oliphant@ling.ed.ac.uk

    http://www.ling.ed.ac.uk/~oliphant/glmame

  This code may be used and distributed under the terms of the
  Mame license

*****************************************************************/
/* pretend we're x11.c otherwise display and a few other crucial things don't
   get declared */
#define __X11_C_   
#define __XOPENGL_C_

#define RRand(range) (random()%range)

#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <windowsx.h>
#include <assert.h>
#include <string.h>
#include <excpt.h>
#include "common.h"
#include "usrintrf.h"
#include "osdepend.h"
#include "mame.h"
#include "driver.h"
#include "MAME32.h"
#include "Display.h"
#include "Sound.h"
#include "Keyboard.h"
#include "Joystick.h"
#include "Trak.h"
#include "resource.h"
#include "M32Util.h"

#include "wgl.h"

/*
#ifndef NOSEAL
#include "SealSound.h"      /* For sound devices. 
#endif
*/

struct GameOptions mame_options;
static void MamePlayGame();
static int              page_index;
static game_data_type*  game_data; 
static int              game_count;

static int  last_sort = 0;

/* global data--know where to send messages */
static BOOL in_emulation;

/* quit after game */
static BOOL quit;

/* idle work at startup */
static BOOL idle_work;
static int  game_index;

int winwidth=640;
int winheight=480;
float fxgamma=1.0;

static HDC thisWin;
static HWND thisHwnd;
/*
static wglWnd thisCwnd;
*/
static HGLRC cx;

static int fx=0;
static int fxwin=0;
extern int screendirty;
extern int doublebuffer;
extern int dodepth;

/***************************************************************************
    Function prototypes
 ***************************************************************************/

static LRESULT CALLBACK     MAME32_MessageProc(HWND, UINT, WPARAM, LPARAM);
static HWND                 MAME32_CreateWindow(void);
static void                 MAME32_ProcessMessages(void);
static BOOL                 MAME32_PumpAndReturnMessage(MSG* pMsg);
static void                 MAME32_Quit(void);
static BOOL                 OnMessage(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam, LRESULT* pResult);
static void                 OnActivateApp(HWND hWnd, BOOL fActivate, DWORD dwThreadId);
static void                 OnSysCommand(HWND hWnd, UINT cmd, int x, int y);
static void                 OnClose(HWND hWnd);

/***************************************************************************
    External variables
 ***************************************************************************/

/*
struct tMAME32App   MAME32App = 
{
    { NULL },                   /* m_hwndUI          
    { NULL },                   /* m_hWnd            
    { "MAME32" },               /* m_pName           
    { FALSE },                  /* m_bIsInitialized  
    { FALSE },                  /* m_bIsActive       
    { FALSE },                  /* m_bPaused         
    { FALSE },                  /* m_bMMXDetected    
    { FALSE },                  /* m_bUseAIMouse     
    { NULL },                   /* m_pDisplay        
    { NULL },                   /* m_pSound          
    { NULL },                   /* m_pKeyboard       
    { NULL },                   /* m_pJoystick       
    { NULL },                   /* m_pTrak           
    { NULL },                   /* m_pFMSynth        

    { MAME32_CreateWindow },            /* CreateMAMEWindow     
    { MAME32_ProcessMessages },         /* ProcessMessages      
    { MAME32_PumpAndReturnMessage },    /* PumpAndReturnMessage 
    { MAME32_Quit },                    /* Quit                 
    { NULL }					/* detect MMX           
};
*/

/***************************************************************************
    Internal structures
 ***************************************************************************/

/***************************************************************************
    Internal variables
 ***************************************************************************/

static BOOL auto_pause;

/***************************************************************************
    External functions  
 ***************************************************************************/

/*
void MAME32App_init(options_type *options)
{
    MAME32App.m_hWnd = NULL;

    MAME32App.m_bIsInitialized = FALSE;
    MAME32App.m_bIsActive      = FALSE;
    MAME32App.m_bIsPaused      = FALSE;

    MAME32App.m_pDisplay    = NULL;
    MAME32App.m_pSound      = NULL;
    MAME32App.m_pKeyboard   = NULL;
    MAME32App.m_pJoystick   = NULL;
    MAME32App.m_pTrak       = NULL;
    MAME32App.m_pFMSynth    = NULL;

    auto_pause = options->auto_pause;

    /*
        Machine->scrbitmap is not initialized in the mame source
        until after the call to osd_create_display().
        This causes a problem if osd_create_display() detects an error,
        then shows the error message box, which causes focus to change,
        which causes OnPause() to be called, which uses Machine->scrbitmap.
        Whew. So it needs to be set to NULL so it doesn't crash in OnPause().
    /
    Machine->scrbitmap = NULL;
}
*/



/***************************************************************************
    Internal OPENGL functions
 ***************************************************************************/

// Color Palette handle
HPALETTE hPalette = NULL;
// Set Pixel Format function - forward declaration
void SetDCPixelFormat(HDC hDC);
HPALETTE GetOpenGLPalette(HDC hDC);
HGLRC tempRC;

static HGLRC get_GC( HDC hDC )
{
        if( hDC == 0 )
			return 0; /* printf( "get_GC: Error, HDC is zero\n"); */

	// Select the pixel format
	SetDCPixelFormat(hDC);

	// Create palette if needed
	hPalette = GetOpenGLPalette(hDC);

    tempRC = wglCreateContext( hDC );

    /* check if the context could be created */
    if( tempRC == NULL ) {
        /* fprintf(stderr, "getGC context could NOT be created \n"); */
        return( 0 );
    }

    /* associated the context with the X window */
    if( wglMakeCurrent( hDC, tempRC ) == FALSE) {
     wglDeleteContext( tempRC );
        return( 0 );
    }

    return tempRC;
}

// Select the pixel format for a given device context
void SetDCPixelFormat(HDC hDC)
{
    int nPixelFormat=0;

    static PIXELFORMATDESCRIPTOR pfd = {
	    sizeof(PIXELFORMATDESCRIPTOR),  // Size of this structure
	    1,                              // Version of this structure
	    PFD_DRAW_TO_WINDOW |            // Draw to Window (not to bitmap)
	    PFD_SUPPORT_OPENGL |	    // Support OpenGL calls in window
	    PFD_DOUBLEBUFFER,               // Double buffered
	    PFD_TYPE_RGBA,                  // RGBA Color mode
	    24,                             // Want 24bit color
	    0,0,0,0,0,0,                    // Not used to select mode
	    0,0,                            // Not used to select mode
	    0,0,0,0,0,                      // Not used to select mode
	    32,                             // Size of depth buffer
	    0,                              // Not used to select mode
	    0,                              // Not used to select mode
	    PFD_MAIN_PLANE,                 // Draw in main plane
	    0,                              // Not used to select mode
	    0,0,0 };                        // Not used to select mode

    // Choose a pixel format that best matches that described in pfd
    nPixelFormat = ChoosePixelFormat(hDC, &pfd);

    // Set the pixel format for the device context
    if(SetPixelFormat(hDC, nPixelFormat, &pfd)==FALSE)
	    MessageBox(thisHwnd, "could not set PixelFormat", "ERROR", 
			       MB_OK|MB_ICONERROR); 

}


// If necessary, creates a 3-3-2 palette for the device context listed.
HPALETTE GetOpenGLPalette(HDC hDC)
{
    HPALETTE hRetPal = NULL;	// Handle to palette to be created
    PIXELFORMATDESCRIPTOR pfd;	// Pixel Format Descriptor
    LOGPALETTE *pPal;			// Pointer to memory for logical palette
    int nPixelFormat;			// Pixel format index
    int nColors;				// Number of entries in palette
    int i;						// Counting variable
    BYTE RedRange,GreenRange,BlueRange;
							    // Range for each color entry (7,7,and 3)


    // Get the pixel format index and retrieve the pixel format description
    nPixelFormat = GetPixelFormat(hDC);
    DescribePixelFormat(hDC, nPixelFormat, sizeof(PIXELFORMATDESCRIPTOR), &pfd);

    // Does this pixel format require a palette?  If not, do not create a
    // palette and just return NULL
    if(!(pfd.dwFlags & PFD_NEED_PALETTE))
	    return NULL;

    // Number of entries in palette.  8 bits yeilds 256 entries
    nColors = 1 << pfd.cColorBits;	

    // Allocate space for a logical palette structure plus all the palette entries
    pPal = (LOGPALETTE*)malloc(sizeof(LOGPALETTE) + nColors*sizeof(PALETTEENTRY));

    // Fill in palette header
    pPal->palVersion = 0x300;		// Windows 3.0
    pPal->palNumEntries = nColors; // table size

    // Build mask of all 1's.  This creates a number represented by having
    // the low order x bits set, where x = pfd.cRedBits, pfd.cGreenBits, and
    // pfd.cBlueBits.  
    RedRange = (1 << pfd.cRedBits) -1;
    GreenRange = (1 << pfd.cGreenBits) - 1;
    BlueRange = (1 << pfd.cBlueBits) -1;

    // Loop through all the palette entries
    for(i = 0; i < nColors; i++)
	    {
	    // Fill in the 8-bit equivalents for each component
	    pPal->palPalEntry[i].peRed = (i >> pfd.cRedShift) & RedRange;
	    pPal->palPalEntry[i].peRed = (unsigned char)(
		    (double) pPal->palPalEntry[i].peRed * 255.0 / RedRange);

	    pPal->palPalEntry[i].peGreen = (i >> pfd.cGreenShift) & GreenRange;
	    pPal->palPalEntry[i].peGreen = (unsigned char)(
		    (double)pPal->palPalEntry[i].peGreen * 255.0 / GreenRange);

	    pPal->palPalEntry[i].peBlue = (i >> pfd.cBlueShift) & BlueRange;
	    pPal->palPalEntry[i].peBlue = (unsigned char)(
		    (double)pPal->palPalEntry[i].peBlue * 255.0 / BlueRange);

	    pPal->palPalEntry[i].peFlags = (unsigned char) NULL;
	    }
	    

    // Create the palette
    hRetPal = CreatePalette(pPal);

    // Go ahead and select and realize the palette for this device context
    SelectPalette(hDC,hRetPal,FALSE);
    RealizePalette(hDC);

    // Free the memory used for the logical palette structure
    free(pPal);

    // Return the handle to the new palette
    return hRetPal;
}


/***************************************************************************
    Internal functions
 ***************************************************************************/

/* Create display */

static BOOL Win32UI_init(HINSTANCE hInstance, LPSTR lpCmdLine, int nCmdShow)
{
    static BOOL     bRegistered = FALSE;

    if (bRegistered == FALSE)
    {
        WNDCLASS    WndClass;

        WndClass.style          = CS_SAVEBITS | CS_BYTEALIGNCLIENT | CS_OWNDC;
        WndClass.lpfnWndProc    = MAME32_MessageProc;
        WndClass.cbClsExtra     = 0;
        WndClass.cbWndExtra     = 0;
        WndClass.hInstance      = hInstance;
        WndClass.hIcon          = LoadIcon(hInstance, MAKEINTATOM(IDI_MAME32_ICON));
        WndClass.hCursor        = LoadCursor(NULL, IDC_ARROW);
        WndClass.hbrBackground  = (HBRUSH)GetStockObject(NULL_BRUSH);
        WndClass.lpszMenuName   = NULL;
        WndClass.lpszClassName  = (LPCSTR)"classMAME32";
        
        if (RegisterClass(&WndClass) == 0)
            return FALSE;
        bRegistered = TRUE;
    }

    thisHwnd = CreateWindowEx(0,
                          "classMAME32",
                          "WGLMAME" ,
                          WS_OVERLAPPEDWINDOW & ~WS_THICKFRAME | WS_BORDER,
                          CW_USEDEFAULT,
                          CW_USEDEFAULT,
                          640, 480,
                          NULL,
                          NULL,
                          hInstance,
                          NULL);

	ShowWindow(thisHwnd, nCmdShow);

	/* thisCwnd.attach(thisHwnd); */
	thisWin = GetDC(thisHwnd);

    wglMakeCurrent(NULL, NULL);

    /* get the graphics context for this widget */
    if( (cx = get_GC( thisWin )) == 0 )
    {
	    MessageBox(thisHwnd, "could not create GLContext", "ERROR", 
			       MB_OK|MB_ICONERROR); 

    } else {
	    MessageBox(thisHwnd, "could create GLContext", "OK", MB_OK); 
    }

    SetFocus(thisHwnd);

	return thisHwnd!=NULL;
}

static LRESULT CALLBACK MAME32_MessageProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam)
{
    LRESULT Result = 0;
	HDC hdc = 0;

	switch(Msg)
	{
		case WM_DESTROY: 
			PostQuitMessage(0);
			return 0L;

		case WM_QUIT:
			OnClose(thisHwnd);
			return 0;

		case WM_PAINT:
			hdc = (HDC) wParam; 
			return DefWindowProc(hWnd, Msg, wParam, lParam);
	}
    return DefWindowProc(hWnd, Msg, wParam, lParam);
}


static void OnClose(HWND hWnd)
{
    /* Don't call DestroyWindow, it will be called by osd_exit. */
    wglMakeCurrent(NULL, NULL);
	DestroyWindow(thisHwnd);
}


static BOOL idle_work;


int WINAPI WinMain(HINSTANCE    hInstance,
                   HINSTANCE    hPrevInstance,
                   LPSTR        lpCmdLine,
                   int          nCmdShow)
{
    MSG     msg;

    if (!Win32UI_init(hInstance, lpCmdLine, nCmdShow))
	{
	    MessageBox(thisHwnd, "could not create window ...", "ERROR", 
			       MB_OK|MB_ICONERROR); 
		OnClose(thisHwnd);
        return 1;
	}

	/* Set the samplerate to 0 if sound is disabled,
	   this should notify mame not to "render" it (speed improvement) */
	Machine->sample_rate = 0;
	mame_options.samplerate = 0;

    /*
        Simplified MFC Run() alg. See mfc/src/thrdcore.cpp.
    */
        /* phase2: pump messages while available */
		while (GetMessage(&msg, NULL, 0, 0)) 
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}

    return 0;
}


void MamePlayGame()
{
	char buf[1000];
	int index = 0;

    if (run_game(index ,&mame_options) != 0)
    {
        const struct RomModule *romp = drivers[index]->rom;

        /* This needs to be changed to use a window with a scrollbar
         * because the list can be too large to fit on the screen.
         */
        sprintf(buf, "Unable to initialize machine emulation.\r\n\r\n"
                     "Most likely you have a corrupt ROM file.\r\n"
                     "The following files must exist in the specified\r\n"
                     "directory or .zip file for %s to run.\r\n\r\n",
                     drivers[index]->description);

        sprintf(buf + strlen(buf), "Directory:\r\n");
        GetCurrentDirectory(sizeof(buf) - strlen(buf), buf + strlen(buf));
        sprintf(buf + strlen(buf), "\\%s\r\n\r\n", drivers[index]->name);
        sprintf(buf + strlen(buf), "or .zip file:\r\n");
        GetCurrentDirectory(sizeof(buf) - strlen(buf), buf + strlen(buf));
        sprintf(buf + strlen(buf), "\\roms\\%s.zip\r\n\r\n", drivers[index]->name);

        sprintf(buf + strlen(buf), "Files:\r\n");
        while (romp->name || romp->offset || romp->length)
        {
            romp++; /* skip memory region definition */

            while (romp->length)
            {
                char name[100];
                int length;

                sprintf(name, romp->name, drivers[index]->name);

                length = 0;

                do
                {
                    /* ROM_RELOAD */
                    if (romp->name == (char *)-1)
                        length = 0; /* restart */

                    length += romp->length & ~0x80000000;

                    romp++;
                } while (romp->length && (romp->name == 0 || romp->name == (char *)-1));

                sprintf(buf + strlen(buf), "%-12s\t%u bytes\n", name, length);
            }
        }

        MessageBox(thisHwnd, buf, "MAME32 Error", MB_OK | MB_ICONERROR);
    }

    in_emulation = FALSE;
    
    if (quit)
    {
       PostMessage(thisHwnd, WM_CLOSE, 0, 0);
       return;
    }

}