home *** CD-ROM | disk | FTP | other *** search
/ Programming a Multiplayer FPS in DirectX / Programming a Multiplayer FPS in DirectX (Companion CD).iso / Source / Chapter 7 / Engine / Engine.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2005-03-29  |  13.8 KB  |  429 lines

  1. //-----------------------------------------------------------------------------
  2. // Engine.h implementation.
  3. // Refer to the Engine.h interface for more details.
  4. //
  5. // Programming a Multiplayer First Person Shooter in DirectX
  6. // Copyright (c) 2004 Vaughan Young
  7. //-----------------------------------------------------------------------------
  8. #include "Engine.h"
  9.  
  10. //-----------------------------------------------------------------------------
  11. // Globals
  12. //-----------------------------------------------------------------------------
  13. Engine *g_engine = NULL;
  14.  
  15. //-----------------------------------------------------------------------------
  16. // Handles Windows messages.
  17. //-----------------------------------------------------------------------------
  18. LRESULT CALLBACK WindowProc( HWND wnd, UINT msg, WPARAM wparam, LPARAM lparam )
  19. {
  20.     switch( msg )
  21.     {
  22.         case WM_ACTIVATEAPP:
  23.             g_engine->SetDeactiveFlag( !wparam );
  24.             return 0;
  25.  
  26.         case WM_DESTROY:
  27.             PostQuitMessage( 0 );
  28.             return 0;
  29.  
  30.         default:
  31.             return DefWindowProc( wnd, msg, wparam, lparam );
  32.     }
  33. }
  34.  
  35. //-----------------------------------------------------------------------------
  36. // The engine class constructor.
  37. //-----------------------------------------------------------------------------
  38. Engine::Engine( EngineSetup *setup )
  39. {
  40.     // Indicate that the engine is not yet loaded.
  41.     m_loaded = false;
  42.  
  43.     // If no setup structure was passed in, then create a default one.
  44.     // Otehrwise, make a copy of the passed in structure.
  45.     m_setup = new EngineSetup;
  46.     if( setup != NULL )
  47.         memcpy( m_setup, setup, sizeof( EngineSetup ) );
  48.  
  49.     // Store a pointer to the engine in a global variable for easy access.
  50.     g_engine = this;
  51.  
  52.     // Prepare and register the window class.
  53.     WNDCLASSEX wcex;
  54.     wcex.cbSize        = sizeof( WNDCLASSEX );
  55.     wcex.style         = CS_CLASSDC;
  56.     wcex.lpfnWndProc   = WindowProc;
  57.     wcex.cbClsExtra    = 0;
  58.     wcex.cbWndExtra    = 0;
  59.     wcex.hInstance     = m_setup->instance;
  60.     wcex.hIcon         = LoadIcon( NULL, IDI_APPLICATION );
  61.     wcex.hCursor       = LoadCursor( NULL, IDC_ARROW );
  62.     wcex.hbrBackground = NULL;
  63.     wcex.lpszMenuName  = NULL;
  64.     wcex.lpszClassName = "WindowClass";
  65.     wcex.hIconSm       = LoadIcon( NULL, IDI_APPLICATION );
  66.     RegisterClassEx( &wcex );
  67.  
  68.     // Initialise the COM using multithreaded concurrency.
  69.     CoInitializeEx( NULL, COINIT_MULTITHREADED );
  70.  
  71.     // Create the Direct3D interface.
  72.     IDirect3D9 *d3d = Direct3DCreate9( D3D_SDK_VERSION );
  73.  
  74.     // Enumerate Direct3D device configurations on the default adapter.
  75.     g_deviceEnumeration = new DeviceEnumeration;
  76.     if( g_deviceEnumeration->Enumerate( d3d ) != IDOK )
  77.     {
  78.         SAFE_RELEASE( d3d );
  79.         return;
  80.     }
  81.  
  82.     // Create the window and retrieve a handle to it.
  83.     m_window = CreateWindow( "WindowClass", m_setup->name, g_deviceEnumeration->IsWindowed() ? WS_OVERLAPPED : WS_POPUP, 0, 0, 800, 600, NULL, NULL, m_setup->instance, NULL );
  84.  
  85.     // Prepare the device presentation parameters.
  86.     D3DPRESENT_PARAMETERS d3dpp;
  87.     ZeroMemory( &d3dpp, sizeof( D3DPRESENT_PARAMETERS ) );
  88.     d3dpp.BackBufferWidth = g_deviceEnumeration->GetSelectedDisplayMode()->Width;
  89.     d3dpp.BackBufferHeight = g_deviceEnumeration->GetSelectedDisplayMode()->Height;
  90.     d3dpp.BackBufferFormat = g_deviceEnumeration->GetSelectedDisplayMode()->Format;
  91.     d3dpp.BackBufferCount = m_setup->totalBackBuffers;
  92.     d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
  93.     d3dpp.hDeviceWindow = m_window;
  94.     d3dpp.Windowed = g_deviceEnumeration->IsWindowed();
  95.     d3dpp.EnableAutoDepthStencil = true;
  96.     d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
  97.     d3dpp.FullScreen_RefreshRateInHz = g_deviceEnumeration->GetSelectedDisplayMode()->RefreshRate;
  98.     if( g_deviceEnumeration->IsVSynced() == true )
  99.         d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_DEFAULT;
  100.     else
  101.         d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
  102.  
  103.     // Destroy the device enumeration object.
  104.     SAFE_DELETE( g_deviceEnumeration );
  105.  
  106.     // Create the Direct3D device.
  107.     if( FAILED( d3d->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, m_window, D3DCREATE_MIXED_VERTEXPROCESSING, &d3dpp, &m_device ) ) )
  108.         return;
  109.  
  110.     // Release the Direct3D interface as it is no longer needed.
  111.     SAFE_RELEASE( d3d );
  112.  
  113.     // Switch lighting off by default.
  114.     m_device->SetRenderState( D3DRS_LIGHTING, false );
  115.  
  116.     // Set the texture filters to use anisotropic texture filtering.
  117.     m_device->SetSamplerState ( 0, D3DSAMP_MAGFILTER, D3DTEXF_ANISOTROPIC );
  118.     m_device->SetSamplerState ( 0, D3DSAMP_MINFILTER, D3DTEXF_ANISOTROPIC );
  119.     m_device->SetSamplerState( 0, D3DSAMP_MIPFILTER, D3DTEXF_LINEAR );
  120.  
  121.     // Set the projection matrix.
  122.     D3DXMATRIX projMatrix;
  123.     D3DXMatrixPerspectiveFovLH( &projMatrix, D3DX_PI / 4, (float)d3dpp.BackBufferWidth / (float)d3dpp.BackBufferHeight, 0.1f / m_setup->scale, 1000.0f / m_setup->scale );
  124.     m_device->SetTransform( D3DTS_PROJECTION, &projMatrix );
  125.  
  126.     // Store the display mode details.
  127.     m_displayMode.Width = d3dpp.BackBufferWidth;
  128.     m_displayMode.Height = d3dpp.BackBufferHeight;
  129.     m_displayMode.RefreshRate = d3dpp.FullScreen_RefreshRateInHz;
  130.     m_displayMode.Format = d3dpp.BackBufferFormat;
  131.  
  132.     // The swap chain always starts on the first back buffer.
  133.     m_currentBackBuffer = 0;
  134.  
  135.     // Create the sprite interface.
  136.     D3DXCreateSprite( m_device, &m_sprite );
  137.  
  138.     // Create the linked lists of states.
  139.     m_states = new LinkedList< State >;
  140.     m_currentState = NULL;
  141.  
  142.     // Create the resource managers.
  143.     m_scriptManager = new ResourceManager< Script >;
  144.  
  145.     // Create the input object.
  146.     m_input = new Input( m_window );
  147.  
  148.     // Create the network object.
  149.     m_network = new Network( m_setup->guid, m_setup->HandleNetworkMessage );
  150.  
  151.     // Create the sound system.
  152.     m_soundSystem = new SoundSystem( m_setup->scale );
  153.  
  154.     // Seed the random number generator with the current time.
  155.     srand( timeGetTime() );
  156.  
  157.     // Allow the application to perform any state setup now.
  158.     if( m_setup->StateSetup != NULL )
  159.         m_setup->StateSetup();
  160.  
  161.     // The engine is fully loaded and ready to go.
  162.     m_loaded = true;
  163. }
  164.  
  165. //-----------------------------------------------------------------------------
  166. // The engine class destructor.
  167. //-----------------------------------------------------------------------------
  168. Engine::~Engine()
  169. {
  170.     // Ensure the engine is loaded.
  171.     if( m_loaded == true )
  172.     {
  173.         // Destroy the states linked lists.
  174.         if( m_currentState != NULL )
  175.             m_currentState->Close();
  176.         SAFE_DELETE( m_states );
  177.  
  178.         // Destroy everything.
  179.         SAFE_DELETE( m_soundSystem );
  180.         SAFE_DELETE( m_network );
  181.         SAFE_DELETE( m_input );
  182.         SAFE_DELETE( m_scriptManager );
  183.  
  184.         // Release the sprite interface.
  185.         SAFE_RELEASE( m_sprite );
  186.  
  187.         // Release the device.
  188.         SAFE_RELEASE( m_device );
  189.     }
  190.  
  191.     // Uninitialise the COM.
  192.     CoUninitialize();
  193.  
  194.     // Unregister the window class.
  195.     UnregisterClass( "WindowClass", m_setup->instance );
  196.  
  197.     // Destroy the engine setup structure.
  198.     SAFE_DELETE( m_setup );
  199. }
  200.  
  201. //-----------------------------------------------------------------------------
  202. // Enters the engine into the main processing loop.
  203. //-----------------------------------------------------------------------------
  204. void Engine::Run()
  205. {
  206.     // Ensure the engine is loaded.
  207.     if( m_loaded == true )
  208.     {
  209.         // Show the window.
  210.         ShowWindow( m_window, SW_NORMAL );
  211.  
  212.         // Used to retrieve details about the viewer from the application.
  213.         ViewerSetup viewer;
  214.  
  215.         // Enter the message loop.
  216.         MSG msg;
  217.         ZeroMemory( &msg, sizeof( MSG ) );
  218.         while( msg.message != WM_QUIT )
  219.         {
  220.             if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) )
  221.             {
  222.                 TranslateMessage( &msg );
  223.                 DispatchMessage( &msg );
  224.             }
  225.             else if( !m_deactive )
  226.             {
  227.                 // Calculate the elapsed time.
  228.                 unsigned long currentTime = timeGetTime();
  229.                 static unsigned long lastTime = currentTime;
  230.                 float elapsed = ( currentTime - lastTime ) / 1000.0f;
  231.                 lastTime = currentTime;
  232.  
  233.                 // Update the network object, processing any pending messages.
  234.                 m_network->Update();
  235.  
  236.                 // Update the input object, reading the keyboard and mouse.
  237.                 m_input->Update();
  238.  
  239.                 // Check if the user wants to make a forced exit.
  240.                 if( m_input->GetKeyPress( DIK_F1 ) )
  241.                     PostQuitMessage( 0 );
  242.  
  243.                 // Request the viewer from the current state, if there is one.
  244.                 if( m_currentState != NULL )
  245.                     m_currentState->RequestViewer( &viewer );
  246.  
  247.                 // Update the current state (if there is one), taking state
  248.                 // changes into account.
  249.                 m_stateChanged = false;
  250.                 if( m_currentState != NULL )
  251.                     m_currentState->Update( elapsed );
  252.                 if( m_stateChanged == true )
  253.                     continue;
  254.  
  255.                 // Begin the scene.
  256.                 m_device->Clear( 0, NULL, viewer.viewClearFlags, 0, 1.0f, 0 );
  257.                 if( SUCCEEDED( m_device->BeginScene() ) )
  258.                 {
  259.                     // Render the current state, if there is one.
  260.                     if( m_currentState != NULL )
  261.                         m_currentState->Render();
  262.  
  263.                     // End the scene and present it.
  264.                     m_device->EndScene();
  265.                     m_device->Present( NULL, NULL, NULL, NULL );
  266.  
  267.                     // Keep track of the index of the current back buffer.
  268.                     if( ++m_currentBackBuffer == m_setup->totalBackBuffers + 1 )
  269.                         m_currentBackBuffer = 0;
  270.                 }
  271.             }
  272.         }
  273.     }
  274.  
  275.     // Destroy the engine.
  276.     SAFE_DELETE( g_engine );
  277. }
  278.  
  279. //-----------------------------------------------------------------------------
  280. // Returns the window handle.
  281. //-----------------------------------------------------------------------------
  282. HWND Engine::GetWindow()
  283. {
  284.     return m_window;
  285. }
  286.  
  287. //-----------------------------------------------------------------------------
  288. // Sets the deactive flag.
  289. //-----------------------------------------------------------------------------
  290. void Engine::SetDeactiveFlag( bool deactive )
  291. {
  292.     m_deactive = deactive;
  293. }
  294.  
  295. //-----------------------------------------------------------------------------
  296. // Returns the scale that the engine is currently running in.
  297. //-----------------------------------------------------------------------------
  298. float Engine::GetScale()
  299. {
  300.     return m_setup->scale;
  301. }
  302.  
  303. //-----------------------------------------------------------------------------
  304. // Returns a pointer to the Direct3D device.
  305. //-----------------------------------------------------------------------------
  306. IDirect3DDevice9 *Engine::GetDevice()
  307. {
  308.     return m_device;
  309. }
  310.  
  311. //-----------------------------------------------------------------------------
  312. // Returns a pointer to the display mode of the current Direct3D device.
  313. //-----------------------------------------------------------------------------
  314. D3DDISPLAYMODE *Engine::GetDisplayMode()
  315. {
  316.     return &m_displayMode;
  317. }
  318.  
  319. //-----------------------------------------------------------------------------
  320. // Returns a pointer to the sprite interface.
  321. //-----------------------------------------------------------------------------
  322. ID3DXSprite *Engine::GetSprite()
  323. {
  324.     return m_sprite;
  325. }
  326.  
  327. //-----------------------------------------------------------------------------
  328. // Adds a state to the engine.
  329. //-----------------------------------------------------------------------------
  330. void Engine::AddState( State *state, bool change )
  331. {
  332.     m_states->Add( state );
  333.  
  334.     if( change == false )
  335.         return;
  336.  
  337.     if( m_currentState != NULL )
  338.         m_currentState->Close();
  339.  
  340.     m_currentState = m_states->GetLast();
  341.     m_currentState->Load();
  342. }
  343.  
  344. //-----------------------------------------------------------------------------
  345. // Removes a state from the engine
  346. //-----------------------------------------------------------------------------
  347. void Engine::RemoveState( State *state )
  348. {
  349.     m_states->Remove( &state );
  350. }
  351.  
  352. //-----------------------------------------------------------------------------
  353. // Changes processing to the state with the specified ID.
  354. //-----------------------------------------------------------------------------
  355. void Engine::ChangeState( unsigned long id )
  356. {
  357.     // Iterate through the list of states and find the new state to change to.
  358.     m_states->Iterate( true );
  359.     while( m_states->Iterate() != NULL )
  360.     {
  361.         if( m_states->GetCurrent()->GetID() == id )
  362.         {
  363.             // Close the old state.
  364.             if( m_currentState != NULL )
  365.                 m_currentState->Close();
  366.  
  367.             // Let the sound system perform garbage collection.
  368.             m_soundSystem->GarbageCollection();
  369.  
  370.             // Set the new current state and load it.
  371.             m_currentState = m_states->GetCurrent();
  372.             m_currentState->Load();
  373.  
  374.             // Swap the back buffers until the first one is in the front.
  375.             while( m_currentBackBuffer != 0 )
  376.             {
  377.                 m_device->Present( NULL, NULL, NULL, NULL );
  378.  
  379.                 if( ++m_currentBackBuffer == m_setup->totalBackBuffers + 1 )
  380.                     m_currentBackBuffer = 0;
  381.             }
  382.  
  383.             // Indicate that the state has changed.
  384.             m_stateChanged = true;
  385.  
  386.             break;
  387.         }
  388.     }
  389. }
  390.  
  391. //-----------------------------------------------------------------------------
  392. // Returns a pointer to the current state.
  393. //-----------------------------------------------------------------------------
  394. State *Engine::GetCurrentState()
  395. {
  396.     return m_currentState;
  397. }
  398.  
  399. //-----------------------------------------------------------------------------
  400. // Returns a pointer to the script manager.
  401. //-----------------------------------------------------------------------------
  402. ResourceManager< Script > *Engine::GetScriptManager()
  403. {
  404.     return m_scriptManager;
  405. }
  406.  
  407. //-----------------------------------------------------------------------------
  408. // Returns a pointer to the input object.
  409. //-----------------------------------------------------------------------------
  410. Input *Engine::GetInput()
  411. {
  412.     return m_input;
  413. }
  414.  
  415. //-----------------------------------------------------------------------------
  416. // Returns a pointer to the network object.
  417. //-----------------------------------------------------------------------------
  418. Network *Engine::GetNetwork()
  419. {
  420.     return m_network;
  421. }
  422.  
  423. //-----------------------------------------------------------------------------
  424. // Returns a pointer to the sound system.
  425. //-----------------------------------------------------------------------------
  426. SoundSystem *Engine::GetSoundSystem()
  427. {
  428.     return m_soundSystem;
  429. }