summaryrefslogtreecommitdiffhomepage
path: root/Stars45/Game.cpp
blob: 7d88bf8f296d4a36494e12115e7620db61772c77 (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
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
/*  Starshatter: The Open Source Project
    Copyright (c) 2021-2022, Starshatter: The Open Source Project Contributors
    Copyright (c) 2011-2012, Starshatter OpenSource Distribution Contributors
    Copyright (c) 1997-2006, Destroyer Studios LLC.

    AUTHOR:       John DiCamillo

*/

#include "MemDebug.h"
#include "Game.h"
#include "Mouse.h"
#include "Universe.h"
#include "Screen.h"
#include "Window.h"
#include "EventDispatch.h"
#include "Color.h"
#include "DataLoader.h"
#include "Keyboard.h"
#include "Panic.h"
#include "Pcx.h"
#include "Bitmap.h"
#include "MachineInfo.h"
#include "Video.h"
#include "VideoFactory.h"
#include "VideoSettings.h"
#include "ContentBundle.h"
#include "Clock.h"

// +--------------------------------------------------------------------+

Game*    game           = 0;

const double MAX_FRAME_TIME_NORMAL  = 1.0 / 5.0;

// +--------------------------------------------------------------------+

Game::Game()
    : world(0), video_factory(0), video(0), video_settings(0), soundcard(0),
      screen(0), totaltime(0),
      hInst(0), hwnd(0),
      status(Game::OK), exit_code(0), window_style(0)
{
    if (!game) {
        game = this;

        active         = false;
        paused         = false;
        server         = false;
        show_mouse     = false;
        frame_number   = 0;

        max_frame_length = MAX_FRAME_TIME_NORMAL;

        video_settings = new(__FILE__,__LINE__) VideoSettings;

        is_windowed             = false;
        is_active               = false;
        is_device_lost          = false;
        is_minimized            = false;
        is_maximized            = false;
        ignore_size_change      = false;
        is_device_initialized   = false;
        is_device_restored      = false;
    }
    else
    status = TOO_MANY;
}

Game::~Game()
{
    if (game == this)
    game = 0;

    delete world;
    delete screen;
    delete video_factory;
    delete video;
    delete soundcard;
    delete video_settings;

    if (status == EXIT)
    ShowStats();
}

// +--------------------------------------------------------------------+

HINSTANCE Game::GetHINST()
{
    if (game)
    return game->hInst;

    return 0;
}

HWND Game::GetHWND()
{
    if (game)
    return game->hwnd;

    return 0;
}

bool Game::IsWindowed()
{
    if (game)
    return game->is_windowed;

    return false;
}

// +--------------------------------------------------------------------+

bool
Game::Init(HINSTANCE hi, HINSTANCE hpi, LPSTR cmdline, int nCmdShow)
{
    status = OK;

    if (status == OK) {
        Print("  Initializing content...\n");
        ContentBundle::GetInstance()->Init();

        Print("  Initializing game...\n");
        if (!InitGame()) {
            if (Panic::Panicked())
            Panic::Panic("Could not initialize the game.");
            status = INIT_FAILED;
        }
    }

    return status == OK;
}

// +--------------------------------------------------------------------+

bool
Game::InitVideo()
{
    if (server) return true;

    // create a video factory, and video object:
    video_factory = new(__FILE__,__LINE__) VideoFactory(hwnd);

    if (video_factory) {
        Print("  Init Video...\n");
        Print("  Request %s mode\n", video_settings->GetModeDescription());

        video = video_factory->CreateVideo(video_settings);

        if (video) {
            if (!video->IsHardware()) {
                video_factory->DestroyVideo(video);
                video = 0;

                Panic::Panic("3D Hardware Not Found");
            }

            // save a copy of the device-specific video settings:
            else if (video->GetVideoSettings()) {
                *video_settings = *video->GetVideoSettings();
                is_windowed = video_settings->IsWindowed();
            }
        }

        soundcard = video_factory->CreateSoundCard();
    }

    return (video && video->Status() == Video::VIDEO_OK);
}

// +--------------------------------------------------------------------+

bool
Game::ResetVideo()
{
    if (server)          return true;
    if (!video_factory)  return InitVideo();

    Print("  Reset Video...\n");
    Print("  Request %s mode\n", video_settings->GetModeDescription());

    delete screen;

    if (video && !video->Reset(video_settings)) {
        video_factory->DestroyVideo(video);
        video = video_factory->CreateVideo(video_settings);
    }

    if (!video || video->Status() != Video::VIDEO_OK) {
        Panic::Panic("Could not re-create Video Interface.");
        return false;
    }

    Print("  Re-created video object.\n");

    // save a copy of the device-specific video settings:
    if (video->GetVideoSettings()) {
        *video_settings = *video->GetVideoSettings();
        is_windowed = video_settings->IsWindowed();
    }

    Color::UseVideo(video);

    screen = new(__FILE__,__LINE__) Screen(video);
    if (!screen) {
        Panic::Panic("Could not re-create Screen object.");
        return false;
    }

    Print("  Re-created screen object.\n");

    if (!screen->SetBackgroundColor(Color::Black))
    Print("  WARNING: could not set video background color to Black\n");

    screen->ClearAllFrames(true);

    Print("  Re-established requested video parameters.\n");

    Bitmap::CacheUpdate();
    Print("  Refreshed texture bitmaps.\n\n");
    return true;
}

// +--------------------------------------------------------------------+

bool
Game::ResizeVideo()
{
    if (!video || !video_settings)   return false;
    if (!is_windowed)                return false;
    if (ignore_size_change)          return true;

    HRESULT  hr = S_OK;
    RECT     client_old;

    client_old = client_rect;

    // Update window properties
    GetWindowRect(hwnd, &bounds_rect);
    GetClientRect(hwnd, &client_rect);

    if (client_old.right   - client_old.left  !=
            client_rect.right  - client_rect.left ||
            client_old.bottom  - client_old.top   !=
            client_rect.bottom - client_rect.top) {

        // A new window size will require a new backbuffer
        // size, so the 3D structures must be changed accordingly.
        Pause(true);

        video_settings->is_windowed   = true;
        video_settings->window_width  = client_rect.right - client_rect.left;
        video_settings->window_height = client_rect.bottom - client_rect.top;

        ::Print("ResizeVideo() %d x %d\n", video_settings->window_width, video_settings->window_height);

        if (video) {
            video->Reset(video_settings);
        }

        Pause(false);
    }

    // save a copy of the device-specific video settings:
    if (video->GetVideoSettings()) {
        *video_settings = *video->GetVideoSettings();
        is_windowed = video_settings->IsWindowed();
    }

    screen->Resize(video_settings->window_width, video_settings->window_height);

    return hr == S_OK;
}

bool
Game::ToggleFullscreen()
{
    bool result = false;

    if (video && video_settings) {
        Pause(true);
        ignore_size_change = true;

        // Toggle the windowed state
        is_windowed = !is_windowed;
        video_settings->is_windowed = is_windowed;

        // Prepare window for windowed/fullscreen change
        AdjustWindowForChange();

        // Reset the 3D device
        if (!video->Reset(video_settings)) {
            // reset failed, try to restore...
            ignore_size_change = false;

            if (!is_windowed) {
                // Restore window type to windowed mode
                is_windowed = !is_windowed;
                video_settings->is_windowed = is_windowed;

                AdjustWindowForChange();

                SetWindowPos(hwnd,
                HWND_NOTOPMOST,
                bounds_rect.left,
                bounds_rect.top,
                bounds_rect.right  - bounds_rect.left,
                bounds_rect.bottom - bounds_rect.top,
                SWP_SHOWWINDOW);
            }

            ::Print("Unable to toggle %s fullscreen mode.\n", is_windowed ? "into" : "out of");
        }

        else {
            ignore_size_change = false;

            // When moving from fullscreen to windowed mode, it is important to
            // adjust the window size after resetting the device rather than
            // beforehand to ensure that you get the window size you want.  For
            // example, when switching from 640x480 fullscreen to windowed with
            // a 1000x600 window on a 1024x768 desktop, it is impossible to set
            // the window size to 1000x600 until after the display mode has
            // changed to 1024x768, because windows cannot be larger than the
            // desktop.

            if (is_windowed) {
                SetWindowPos(hwnd,
                HWND_NOTOPMOST,
                bounds_rect.left,
                bounds_rect.top,
                bounds_rect.right  - bounds_rect.left,
                bounds_rect.bottom - bounds_rect.top,
                SWP_SHOWWINDOW);
            }

            GetClientRect(hwnd, &client_rect);  // Update our copy
            Pause(false);

            if (is_windowed)
            screen->Resize(video_settings->window_width,
            video_settings->window_height);

            else
            screen->Resize(video_settings->fullscreen_mode.width,
            video_settings->fullscreen_mode.height);

            result = true;
        }
    }

    return result;
}

bool
Game::AdjustWindowForChange()
{
    if (is_windowed) {
        // Set windowed-mode style
        SetWindowLong(hwnd, GWL_STYLE, window_style);
        if (hmenu != NULL) {
            SetMenu(hwnd, hmenu);
            hmenu = NULL;
        }
    }
    else {
        // Set fullscreen-mode style
        SetWindowLong(hwnd, GWL_STYLE, WS_POPUP|WS_SYSMENU|WS_VISIBLE);
        if (hmenu == NULL) {
            hmenu = GetMenu(hwnd);
            SetMenu(hwnd, NULL);
        }
    }

    return true;
}


// +--------------------------------------------------------------------+

bool
Game::InitGame()
{
    if (server) {
        Print("  InitGame() - server mode.\n");
    }

    else {
        if (!InitVideo() || !video || video->Status() != Video::VIDEO_OK) {
            if (Panic::Panicked())
            Panic::Panic("Could not create the Video Interface.");
            return false;
        }

        Print("  Created video object.\n");

        Color::UseVideo(video);

        screen = new(__FILE__,__LINE__) Screen(video);
        if (!screen) {
            if (Panic::Panicked())
            Panic::Panic("Could not create the Screen object.");
            return false;
        }

        Print("  Created screen object.\n");

        if (!screen->SetBackgroundColor(Color::Black))
        Print("  WARNING: could not set video background color to Black\n");
        screen->ClearAllFrames(true);

        Print("  Established requested video parameters.\n\n");
    }

    return true;
}

// +--------------------------------------------------------------------+

int
Game::Run()
{
    MSG msg;

    status = RUN;
    Print("\n");
    Print("+====================================================================+\n");
    Print("|                              RUN                                   |\n");
    Print("+====================================================================+\n");

    // Polling messages from event queue until quit
    clock.Set();
    while (status < EXIT && !Panic::Panicked()) {
        if (PeekMessage(&msg, hwnd, 0, 0, PM_REMOVE)) {
            if (msg.message == WM_QUIT)
            break;

            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
        else {
            if (GameLoop())
            WaitMessage();
        }
    }

    return exit_code ? exit_code : msg.wParam;
}

// +--------------------------------------------------------------------+

void
Game::Exit()
{
    Print("\n\n*** Game::Exit()\n");
    status = EXIT;
}

// +--------------------------------------------------------------------+

void
Game::Activate(bool f)
{
    active = f;

    if (active && video)
    video->InvalidateCache();
}

// +--------------------------------------------------------------------+

void
Game::Pause(bool f)
{
    if (f) {
        if (soundcard)
        soundcard->Pause();
        paused = true;
    }
    else {
        if (soundcard)
        soundcard->Resume();
        paused = false;
    }
}

// +--------------------------------------------------------------------+

bool
Game::GameLoop()
{
    bool wait_for_windows_events = true;

    if (active && !paused) {
        if (!server) {
            // Route Events to EventTargets
            EventDispatch* ed = EventDispatch::GetInstance();
            if (ed)
            ed->Dispatch();
        }

        UpdateWorld();
        GameState();

        if (!server) {
            UpdateScreen();
            CollectStats();
        }

        wait_for_windows_events = false;
    }
    else if (active && paused) {
        if (GetKey()=='P')
        Pause(false);
    }

    clock.Step();
    frame_number++;
    Mouse::w = 0;
    return wait_for_windows_events;
}

// +--------------------------------------------------------------------+

void
Game::UpdateWorld()
{
    if (world)
    world->ExecFrame(clock.Delta());
}

// +--------------------------------------------------------------------+

void
Game::GameState()
{
}

// +--------------------------------------------------------------------+

void
Game::UpdateScreen()
{
    if (!screen || !video) return;

    if (screen->Refresh()) {
        video->Present();
    }
    else {
        Panic::Panic("Screen refresh failed.");
    }
}

// +--------------------------------------------------------------------+

Game*
Game::GetInstance()
{
    return game;
}

// +--------------------------------------------------------------------+

void
Game::CollectStats()
{
    if (!totaltime) totaltime = clock.RealTime();

    if (video) {
        stats.nframe  = video->GetStats().nframe;
        stats.nverts  = video->GetStats().nverts;
        stats.npolys  = video->GetStats().npolys;
        stats.nlines  = video->GetStats().nlines;
        stats.ncalls += video->GetStats().ncalls;

        stats.total_verts += stats.nverts;
        stats.total_polys += stats.npolys;
        stats.total_lines += stats.nlines;
    }
}

// +--------------------------------------------------------------------+

void
Game::ShowStats()
{
    if (server) return;

    totaltime = clock.RealTime() - totaltime;

    Print("\n");
    Print("Performance Data:\n");
    Print("-----------------\n");

    Print("   Time:            %d msec\n", totaltime);
    Print("   Frames:          %d\n", stats.nframe);
    Print("   Polys Rendered:  %d\n", stats.total_polys);
    Print("   Lines Rendered:  %d\n", stats.total_lines);
    Print("   Verts Rendered:  %d\n", stats.total_verts);
    Print("   Render Calls:    %d\n", stats.ncalls);
    Print("\n");

    Print("Performance Statistics:\n");
    Print("-----------------------\n");

    Print("   Frames/Second:   %.2f\n", (stats.nframe * 1000.0)      / totaltime);
    Print("   Polys/Frame:     %.2f\n", (double) stats.total_polys   / (double) stats.nframe);
    Print("   Polys/Call:      %.2f\n", (double) stats.total_polys   / (double) stats.ncalls);
    Print("   Polys/Second:    %.2f\n", (stats.total_polys * 1000.0) / totaltime);
    Print("   Lines/Second:    %.2f\n", (stats.total_lines * 1000.0) / totaltime);
    Print("   Verts/Second:    %.2f\n", (stats.total_verts * 1000.0) / totaltime);

    Print("\n");
}

// +====================================================================+
// WndProc
// +====================================================================+

#ifndef WM_MOUSEWHEEL
#define WM_MOUSEWHEEL 0x20A
#endif

LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM uParam, LPARAM lParam)
{
    switch (message) {
    case WM_SYSKEYDOWN:
        if (uParam == VK_TAB || uParam == VK_F4)
        return DefWindowProc(hwnd, message, uParam, lParam);

        return 0;

    case WM_MENUCHAR:
        return MNC_CLOSE << 16;

    case WM_ACTIVATEAPP:
        // Keep track of whether or not the app is in the foreground
        if (game)
        game->Activate(uParam?true:false);
        break;

    case WM_PAINT:
        if (!game || !game->OnPaint())
        return DefWindowProc(hwnd, message, uParam, lParam);
        break;

    case WM_SETCURSOR:
        if (game && game->ShowMouse()) {
            return DefWindowProc(hwnd, message, uParam, lParam);
        }
        else {
            // hide the windows mouse cursor
            SetCursor(NULL);
            return 1;
        }
        break;

    case WM_ENTERSIZEMOVE:
        // Halt frame movement while the app is sizing or moving
        if (game)
        game->Pause(true);
        break;

    case WM_SIZE:
        // Pick up possible changes to window style due to maximize, etc.
        if (game && game->hwnd != NULL ) {
            game->window_style = GetWindowLong(game->hwnd, GWL_STYLE );

            if (uParam == SIZE_MINIMIZED) {
                game->Pause(true); // Pause while we're minimized
                game->is_minimized = true;
                game->is_maximized = false;
            }

            else if (uParam == SIZE_MAXIMIZED) {
                if (game->is_minimized)
                game->Pause(false); // Unpause since we're no longer minimized

                game->is_minimized = false;
                game->is_maximized = true;
                game->ResizeVideo();
            }

            else if (uParam == SIZE_RESTORED) {
                if (game->is_maximized) {
                    game->is_maximized = false;
                    game->ResizeVideo();
                }

                else if (game->is_minimized) {
                    game->Pause(false); // Unpause since we're no longer minimized
                    game->is_minimized = false;
                    game->ResizeVideo();
                }
                else {
                    // If we're neither maximized nor minimized, the window size
                    // is changing by the user dragging the window edges.  In this
                    // case, we don't reset the device yet -- we wait until the
                    // user stops dragging, and a WM_EXITSIZEMOVE message comes.
                }
            }
        }
        break;

    case WM_EXITSIZEMOVE:
        if (game) {
            game->Pause(false);
            game->ResizeVideo();
        }
        break;


    case WM_ENTERMENULOOP:
        if (game)
        game->Pause(true);
        break;

    case WM_EXITMENULOOP:
        if (game)
        game->Pause(false);
        break;

        /*
case WM_HELP:
    if (game)
        return game->OnHelp();
    break;
*/

    case WM_KEYDOWN:
        BufferKey(uParam);
        return 0;

    case WM_DESTROY:
        PostQuitMessage(0);
        break;

    case WM_MOUSEMOVE:
        Mouse::x = LOWORD(lParam);
        Mouse::y = HIWORD(lParam);
        break;

    case WM_LBUTTONDOWN:
        Mouse::l = 1;
        break;

    case WM_LBUTTONDBLCLK:
        Mouse::l = 2;
        break;

    case WM_LBUTTONUP:
        Mouse::l = 0;
        break;

    case WM_MBUTTONDOWN:
        Mouse::m = 1;
        break;

    case WM_MBUTTONDBLCLK:
        Mouse::m = 2;
        break;

    case WM_MBUTTONUP:
        Mouse::m = 0;
        break;

    case WM_RBUTTONDOWN:
        Mouse::r = 1;
        break;

    case WM_RBUTTONDBLCLK:
        Mouse::r = 2;
        break;

    case WM_RBUTTONUP:
        Mouse::r = 0;
        break;

    case WM_MOUSEWHEEL:
        {
            int w = (int) (uParam >> 16);
            if (w > 32000) w -= 65536;
            Mouse::w += w;
        }
        break;

    case WM_CLOSE:
        if (game) // && game->Server())
        game->Exit();
        break;

    default:
        return DefWindowProc(hwnd, message, uParam, lParam);
    }

    return 0;
}

// +====================================================================+

const int MAX_KEY_BUF = 512;
static int vkbuf[MAX_KEY_BUF];
static int vkshiftbuf[MAX_KEY_BUF];
static int vkins = 0;
static int vkext = 0;

void
FlushKeys()
{
    Keyboard::FlushKeys();
    vkins = vkext = 0;
}

void
BufferKey(int vkey)
{
    if (vkey < 1) return;

    int shift = 0;

    if (GetAsyncKeyState(VK_SHIFT))
    shift |= 1;

    if (GetAsyncKeyState(VK_CONTROL))
    shift |= 2;

    if (GetAsyncKeyState(VK_MENU))
    shift |= 4;

    vkbuf[vkins] = vkey;
    vkshiftbuf[vkins++] = shift;

    if (vkins >= MAX_KEY_BUF)
    vkins = 0;

    if (vkins == vkext) {
        vkext++;
        if (vkext >= MAX_KEY_BUF)
        vkext = 0;
    }
}

int
GetKey()
{
    if (vkins == vkext) return 0;

    int result = vkbuf[vkext++];
    if (vkext >= MAX_KEY_BUF)
    vkext = 0;

    return result;
}

int
GetKeyPlus(int& key, int& shift)
{
    if (vkins == vkext) return 0;

    key = vkbuf[vkext];
    shift = vkshiftbuf[vkext++];

    if (vkext >= MAX_KEY_BUF)
    vkext = 0;

    return key;
}

// +====================================================================+

Clock*
Game::GetClock()
{
    return &clock;
}


DWORD Game::Frame()
{
    return frame_number;
}