Esempio n. 1
0
/*
================
rvGEApp::Initialize

Initialize the gui editor application
================
*/
bool rvGEApp::Initialize ( void )
{
	mOptions.Init();

	// Mutually exclusive
	com_editors = EDITOR_GUI;

	Sys_GrabMouseCursor( false );

	// Load the options
	mOptions.Load ( );

	mInstance = win32.hInstance;

	// Create the accelerators
	mAccelerators = LoadAccelerators ( mInstance, MAKEINTRESOURCE(IDR_GUIED_ACCELERATORS) );

	// Register the window classes for the main frame and the mdi child window
	WNDCLASSEX wndClass;
	memset ( &wndClass, 0, sizeof(wndClass) );
	wndClass.cbSize = sizeof(WNDCLASSEX);
	wndClass.lpszClassName	= "QUAKE4_GUIEDITOR_CLASS";
	wndClass.lpfnWndProc	= FrameWndProc;
	wndClass.hbrBackground	= (HBRUSH) (COLOR_APPWORKSPACE + 1);
	wndClass.hCursor		= LoadCursor((HINSTANCE) NULL, IDC_ARROW);
	wndClass.lpszMenuName	= MAKEINTRESOURCE(IDR_GUIED_MAIN);
	wndClass.hInstance		= mInstance;
	RegisterClassEx ( &wndClass );

	wndClass.lpszMenuName	= NULL;
	wndClass.lpfnWndProc	= MDIChildProc;
	wndClass.lpszClassName	= "QUAKE4_GUIEDITOR_CHILD_CLASS";
	wndClass.style			= CS_OWNDC|CS_DBLCLKS|CS_BYTEALIGNWINDOW|CS_VREDRAW|CS_HREDRAW;
	wndClass.hbrBackground	= (HBRUSH)GetStockObject( LTGRAY_BRUSH );
	RegisterClassEx ( &wndClass );

	// Create the main window
	mMDIFrame = CreateWindow ( "QUAKE4_GUIEDITOR_CLASS",
							  "Quake IV GUI Editor",
							  WS_OVERLAPPEDWINDOW | WS_CLIPSIBLINGS,
							  CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
							  NULL, NULL, mInstance, (LPVOID)this );

	if ( !mMDIFrame )
	{
		return false;
	}

	SetClassLong( mMDIFrame, GCL_HICON, ( LONG )LoadIcon( win32.hInstance, MAKEINTRESOURCE( IDI_GUIED ) ) );

	// Create the MDI window
	CLIENTCREATESTRUCT ccs;
	ccs.hWindowMenu = GetSubMenu ( GetMenu ( mMDIFrame ), 5 );
	ccs.idFirstChild = IDM_WINDOWCHILD;
	mMDIClient = CreateWindow ( "MDICLIENT", NULL,
								WS_CHILDWINDOW | WS_CLIPSIBLINGS | WS_CLIPCHILDREN,
								0, 0, 1000, 1000,
								mMDIFrame, NULL,
								mInstance, &ccs );

	if ( !mMDIClient )
	{
		DestroyWindow ( mMDIFrame );
		return false;
	}

	// hide the doom window by default
	::ShowWindow ( win32.hWnd, SW_HIDE );

	// Show both windows
	mOptions.GetWindowPlacement ( "mdiframe", mMDIFrame );
	ShowWindow ( mMDIFrame, SW_SHOW );
	UpdateWindow ( mMDIFrame );

	ShowWindow ( mMDIClient, SW_SHOW );
	UpdateWindow ( mMDIClient );

	return true;
}
Esempio n. 2
0
/***********************************************************************************
WinMain - Entry point for program.
***********************************************************************************/
int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,
                   LPSTR lpCmdLine, int nCmdShow)
{
    
    CLog *pLog = CLog::Instance();
    pLog->Log(" ");
    pLog->Log("***************************************");
    pLog->Log("Program Start"); 
    pLog->LogDate();   
    pLog->Log("***************************************");
    
    //request player choose fullscreen or windowed mode
    CConfigData cfg;
    cfg.LoadConfigFile("assets//data//config.cfg");
    bool bFullscreen = false;
    
    bFullscreen = cfg.FullScreen;
    int msgReturn = ::MessageBox(NULL, "Fullscreen? (Y/N)", "Select Display Option", MB_YESNO);
    if(msgReturn == IDYES)
      bFullscreen = true;

    //variable declarations
    CGameData gameData;
    CTimer gTimerFPS;
    int gLoopCount = 0;
    int gSecondCount = 0;
    bool g_bRunning = true;
    bool gExitProgram = false; //this is set true with ESC, for rendering to stop properly
    if(bFullscreen == true)
      gameData.m_windowedYOffset = 0;
    else
      gameData.m_windowedYOffset = 21;

    //determine if we play new or saved game
    /*
    gameData.m_playNewGame = true;
    HRESULT hr = ::MessageBox(0, "Play new game?", "New or saved game!", MB_YESNO);
    if(hr == IDYES)
      gameData.m_playNewGame = true;
    else
      gameData.m_playNewGame = false;
    */
    //gameData.m_playNewGame = true;

    //setup game data    

    pLog->Log("Program Name", cfg.ProgramName);
    pLog->Log("Version", cfg.ProgramVersion);

    //create window
    HWND hWnd;
    WNDCLASSEX wc;
    ZeroMemory(&wc, sizeof(WNDCLASSEX));
    wc.cbSize = sizeof(WNDCLASSEX);
    wc.style = CS_HREDRAW | CS_VREDRAW;
    wc.lpfnWndProc = (WNDPROC)WindowProc;
    wc.hInstance = hInstance;
    wc.hCursor = LoadCursor(NULL, IDC_ARROW);
    wc.lpszClassName = "WindowClass";
    wc.hIconSm = LoadIcon (hInstance, MAKEINTRESOURCE(IDI_ICON1)); 
    RegisterClassEx(&wc);
        
    //screen data - need at least 800x600 

	if(!bFullscreen)
	{
		if(cfg.ScreenWidth < 800)
		{
			cfg.ScreenWidth = 800;   
		}
    	if(cfg.ScreenHeight < 600)
		{
			cfg.ScreenHeight = 600;    
		}
	}
	cfg.ScreenLeft = 0;
    cfg.ScreenTop = 0;

    //create window
    std::string sCaption = cfg.ProgramName + " - " + cfg.ProgramVersion;
    hWnd = CreateWindowEx(NULL,
                          "WindowClass",
                          sCaption.c_str(), //cfg.ProgramVersion.c_str(),  
                          bFullscreen == true ? WS_EX_TOPMOST | WS_POPUP : WS_BORDER | WS_CAPTION | WS_SYSMENU,  
                          cfg.ScreenLeft, cfg.ScreenTop, 
                          bFullscreen == true ? CW_USEDEFAULT : cfg.ScreenWidth, 
                          bFullscreen == true ? CW_USEDEFAULT : cfg.ScreenHeight,
                          NULL,NULL,hInstance,NULL);
    ShowWindow(hWnd, nCmdShow);
    pLog->Log("Window Loaded and Displayed!");
    gameData.m_hWnd = hWnd;

    // set up and initialize Direct3D
	CGraphics con(hWnd, cfg.ScreenWidth, cfg.ScreenHeight, cfg.RefreshRate, (D3DFORMAT)cfg.Format, cfg.Adapter, bFullscreen);

    if(con.InitializeDirectX() == false)
	{
      ::MessageBox(hWnd, "Failed to Create IDirect3D9 Interface.", "Error", 0);
      return 0;
    }
	if(con.IsDisplayModeSupported() == false)
	{
	//	::MessageBox(hWnd, "Display mode not supported.", "Error", 0);
  //    	return 0;
	}
	if(con.InitializeDevice() == false)
	{
      ::MessageBox(hWnd, "Could not create IDirect3DDevice9 Device.", "Error", 0);
      return 0;
    }




    //load framework assets
    if(con.LoadAssetFile(cfg.FrameworkAssetFile) == false){
      pLog->Log("Failure loading " + cfg.FrameworkAssetFile);
      ::MessageBox(hWnd,"Failed to load editor.dat file", "Error", 0);
      return 0;
    }
    else
      pLog->Log(cfg.FrameworkAssetFile + " (frame graphics) was loaded successfully!");

    //load game play assets
    if(con.LoadAssetFile(cfg.GamePlayAssetFile) == false){
      pLog->Log("Failure loading " + cfg.GamePlayAssetFile);
      ::MessageBox(hWnd,"Failed to load assets.dat file", "Error", 0);
      return 0;
    }
    else
      pLog->Log(cfg.GamePlayAssetFile + " (game play graphics) was loaded successfully!");

     //load objects
    //***************************************************************************
    if(gameData.LoadObjectFile(cfg.GameObjectFile) == false){
      pLog->Log("Failure loading " + cfg.GameObjectFile);
      //::MessageBox(hWnd,"Failed to load objects.dat file", "Error", 0);
     // return 0;
    }
    else{
      pLog->Log(cfg.GameObjectFile + " (objects file) was loaded successfully!");
     // for(int i = 0; i < gameData.m_catalog.GetTableSize();++i){
//        pLog->Log("object", gameData.m_catalog.GetTerm(i, 0), gameData.m_catalog.GetTerm(i, 2));
     // }
    }

    gTimerKey.Initialize();
    gTimerKey.ResetTimer();
    mouse.SetHandle(hWnd);
    gTimerFPS.Initialize();
    
    //game timer for update
    CTimer timerGame;
    timerGame.Initialize();

    //define events for changing game states
    //*************************************************************************
    //g_pStateIntro->AddTransitionEvent(EVENT_GO_PLAY1, g_pStatePlay1);
    //g_pStatePlay1->AddTransitionEvent(EVENT_GO_CREDITS, g_pStateCredits);   
    g_pStateIntro->AddTransitionEvent(EVENT_GO_MAIN, g_pStateMain);
    g_pStateMain->AddTransitionEvent(EVENT_GO_PLAY1, g_pStatePlay1);
    g_pStateMain->AddTransitionEvent(EVENT_GO_HELP, g_pStateHelp);
    g_pStateMain->AddTransitionEvent(EVENT_GO_CREDITS, g_pStateCredits);
    g_pStatePlay1->AddTransitionEvent(EVENT_GO_QUIT, g_pStateQuit);
    //g_pStatePlay1->AddTransitionEvent(EVENT_GO_MAIN, g_pStateMain);

    g_pStateHelp->AddTransitionEvent(EVENT_GO_MAIN, g_pStateMain);
    g_pStateCredits->AddTransitionEvent(EVENT_GO_QUIT, g_pStateQuit);    
    g_pCurrent = g_pStatePlay1;// g_pStateIntro;

    //************************************** S O U N D ************************
    //initialize sound manager
    //audio setup
    //CAudioManager *pAudio = CAudioManager::Instance();
    //pAudio->LoadFile("assets\\data\\sounds.dat");

    //load sound asset file
    //pAudio->LoadFile(cfg.SoundAssetFile);
/*
    if(pAudio->LoadFile(cfg.SoundAssetFile) == false){
      pLog->Log("Failure loading " + cfg.GamePlayAssetFile);//assets.dat audio files!");
      ::MessageBox(hWnd,"Failed to load assets.dat audio files!", "Error", 0);
    }
    else
      pLog->Log(cfg.GamePlayAssetFile + " (audio) was loaded successfully!");
  */      
/*
    if(pAudio->IsValidSound() == true)
      pLog->Log("Audio system initialized (size)", pAudio->Size());
    else
      pLog->Log("Audio failure!");
*/
    //log all audio files    
    if(cfg.LogDebugInfo == true){
      pLog->Log("************************** Audio Files Loaded **************");
//      for(int i = 0; i < pAudio->Size(); i++){
//        pLog->Log(pAudio->GetFilename(i)); 
//      }
      pLog->Log("");
    }

    // enter the main loop
    //************************************** M A I N  L O O P *****************
    MSG msg;
    pLog->Log("Entering Main Control Loop");
    float timeDiff = 0.0f;
    g_pCurrent->Activate(gameData, cfg, con);

	int iLost = 0;
    //*********************
    // PYRO
    //con.InitializePyro();
    while(g_bRunning)
    {
      DWORD starting_point = GetTickCount();
      ::Sleep(1);
      if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
      {
          if (msg.message == WM_QUIT)
              break;

          TranslateMessage(&msg);
          DispatchMessage(&msg);
      }

      //manage frame count determination
      gLoopCount++;
      if(gTimerFPS.getTimer(1.0) == true){
        gameData.m_FPS = static_cast<float>(gLoopCount);
        gLoopCount = 0;   
        gSecondCount++;
        if(gSecondCount > 30){ //log every 30 seconds
          gSecondCount = 0;
          if(cfg.LogDebugInfo == true)
            pLog->Log("FPS",gameData.m_FPS);
        }
      }

      //stores mouse button status for use in other classes
      gameData.m_bLeftMouseDown =  mouse.LeftButtonDown();
      gameData.m_bRightMouseDown = mouse.RightButtonDown();
      
      //update
      g_pLast = g_pCurrent;
      g_pNext = g_pCurrent->Update(timerGame.getTimeDifference(), gameData, cfg, con);

      if(g_pNext == g_pStateQuit)
        g_bRunning = false;
      else if(NULL != g_pNext)
	    {
        if(g_pNext != g_pLast){
          g_pLast->Deactivate(gameData, cfg, con);
          g_pCurrent = g_pNext;
          g_pCurrent->Activate(gameData, cfg, con);
        }
      }  
      
iLost = g_pCurrent->IsLost(con, cfg);

if(iLost == 0)
{
	g_pCurrent->Render(con, gameData, cfg);
}
else if(iLost == 2)
{
	g_bRunning = false;
}


      // check the 'escape' key
      if(g_bRunning == false){
        gExitProgram = true;
        PostMessage(hWnd, WM_DESTROY, 0, 0);
      }
    }
    pLog->Log("Exited main loop");
    
    //**************************
    // PYRO
    //con.ClosePyro();
    
    // clean up DirectX and COM
    con.CleanupDirectX();
    Shutdown();

    pLog->Log("DirectX Cleaned Up");
    pLog->Log("Shutdown complete!");
    pLog->Log("***************************************");
    pLog->Log(" Program Terminated Normally");
    pLog->Log("***************************************");

    return static_cast<int>(msg.wParam);
}
Esempio n. 3
0
int WINAPI WinMain( HINSTANCE hInstance,
		    HINSTANCE hPreInstance,
		    LPSTR cmdLine,
		    int cmdShow ){

  HWND hWnd;
  WNDCLASSEX wc;

  wc.cbSize = sizeof(WNDCLASSEX);
  wc.style = CS_HREDRAW | CS_VREDRAW;
  wc.lpfnWndProc = WindowProc;
  wc.cbClsExtra = 0;
  wc.cbWndExtra = 0;
  wc.hInstance = hInstance;
  wc.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ICON1));
  wc.hCursor = LoadCursor(NULL, IDC_ARROW);
  wc.hbrBackground = NULL;
  wc.lpszMenuName = MAKEINTRESOURCE(IDR_MENU1);
  wc.lpszClassName = g_windowClassName;
  wc.hIconSm = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ICON1));

  if( !RegisterClassEx(&wc) ){
    MessageBox( NULL, "Registration Failed!", "ERROR", 0 );
    return 0;
  }

  hWnd = CreateWindowEx( NULL,
			 g_windowClassName,
			 g_applicationName,
			 WS_OVERLAPPED | WS_VISIBLE | WS_CAPTION | WS_SYSMENU,
			 GetSystemMetrics(SM_CXSCREEN)/2 - WINDOWWIDTH/2,
			 GetSystemMetrics(SM_CYSCREEN)/2 - WINDOWHEIGHT/2,
			 WINDOWWIDTH,
			 WINDOWHEIGHT,
			 NULL,
			 NULL,
			 hInstance,
			 NULL );

  if( !hWnd ){
    MessageBox( NULL, "CreateWindow Failed!", "ERROR", 0 );
  }

  g_hwndToolbar = CreateToolbar( hWnd, hInstance );

  SendMessage( hWnd, UM_TOOLBAR_HAS_BEEN_CREATED, NULL, NULL );

  g_pathFinder->CreateGraph( NUMCELLSX, NUMCELLSY );

  MSG msg;
  while(GetMessage( &msg, NULL, 0, 0 )){
    TranslateMessage(&msg);
    DispatchMessage(&msg);
  }

  delete g_pathFinder;

  UnregisterClass( g_windowClassName, wc.hInstance );

  return msg.wParam;
}
Esempio n. 4
0
int
main(int argc, char *argv[])
{
    HRESULT hr;

    HINSTANCE hInstance = GetModuleHandle(NULL);

    WNDCLASSEX wc = {
        sizeof(WNDCLASSEX),
        CS_CLASSDC,
        DefWindowProc,
        0,
        0,
        hInstance,
        NULL,
        NULL,
        NULL,
        NULL,
        "SimpleDX10",
        NULL
    };
    RegisterClassEx(&wc);

    const int WindowWidth = 250;
    const int WindowHeight = 250;
    BOOL Windowed = TRUE;

    DWORD dwStyle = WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_OVERLAPPEDWINDOW;

    RECT rect = {0, 0, WindowWidth, WindowHeight};
    AdjustWindowRect(&rect, dwStyle, FALSE);

    HWND hWnd = CreateWindow(wc.lpszClassName,
                             "Simple example using DirectX10",
                             dwStyle,
                             CW_USEDEFAULT, CW_USEDEFAULT,
                             rect.right - rect.left,
                             rect.bottom - rect.top,
                             NULL,
                             NULL,
                             hInstance,
                             NULL);
    if (!hWnd) {
        return 1;
    }

    ShowWindow(hWnd, SW_SHOW);

    UINT Flags = 0;
    if (LoadLibraryA("d3d10sdklayers")) {
        Flags |= D3D10_CREATE_DEVICE_DEBUG;
    }

    hr = CreateDXGIFactory1(IID_IDXGIFactory1, (void**)(&g_pFactory) );
    if (FAILED(hr)) {
        return 1;
    }

    hr = g_pFactory->EnumAdapters(0, &g_pAdapter);
    if (FAILED(hr)) {
        return 1;
    }

    hr = D3D10CreateDevice1(g_pAdapter,
                            D3D10_DRIVER_TYPE_HARDWARE,
                            NULL,
                            Flags,
                            D3D10_FEATURE_LEVEL_10_0,
                            D3D10_1_SDK_VERSION,
                            &g_pDevice);
    if (FAILED(hr)) {
        return 1;
    }

    DXGI_SWAP_CHAIN_DESC SwapChainDesc;
    ZeroMemory(&SwapChainDesc, sizeof SwapChainDesc);
    SwapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;;
    SwapChainDesc.BufferDesc.RefreshRate.Numerator = 60;
    SwapChainDesc.BufferDesc.RefreshRate.Denominator = 1;
    SwapChainDesc.SampleDesc.Quality = 0;
    SwapChainDesc.SampleDesc.Count = 1;
    SwapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
    SwapChainDesc.BufferCount = 2;
    SwapChainDesc.OutputWindow = hWnd;
    SwapChainDesc.Windowed = true;
    SwapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;

    hr = g_pFactory->CreateSwapChain(g_pDevice, &SwapChainDesc, &g_pSwapChain);
    if (FAILED(hr)) {
        return 1;
    }

    ID3D10RenderTargetView *pRenderTargetView = NULL;
    ID3D10Texture2D* pBackBuffer;
    hr = g_pSwapChain->GetBuffer(0, IID_ID3D10Texture2D, (void **)&pBackBuffer);
    if (FAILED(hr)) {
        return 1;
    }
    D3D10_RENDER_TARGET_VIEW_DESC RenderTargetViewDesc;
    ZeroMemory(&RenderTargetViewDesc, sizeof RenderTargetViewDesc);
    RenderTargetViewDesc.Format = SwapChainDesc.BufferDesc.Format;
    RenderTargetViewDesc.ViewDimension = D3D10_RTV_DIMENSION_TEXTURE2D;
    RenderTargetViewDesc.Texture2D.MipSlice = 0;
    hr = g_pDevice->CreateRenderTargetView(pBackBuffer, &RenderTargetViewDesc, &pRenderTargetView);
    if (FAILED(hr)) {
        return 1;
    }
    pBackBuffer->Release();

    g_pDevice->OMSetRenderTargets(1, &pRenderTargetView, NULL);

    const float clearColor[4] = { 0.3f, 0.1f, 0.3f, 1.0f };
    g_pDevice->ClearRenderTargetView(pRenderTargetView, clearColor);

    ID3D10VertexShader * pVertexShader;
    hr = g_pDevice->CreateVertexShader(g_VS, sizeof g_VS, &pVertexShader);
    if (FAILED(hr)) {
        return 1;
    }

    struct Vertex {
        float position[4];
        float color[4];
    };

    static const D3D10_INPUT_ELEMENT_DESC InputElementDescs[] = {
        { "POSITION", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, offsetof(Vertex, position), D3D10_INPUT_PER_VERTEX_DATA, 0 },
        { "COLOR",    0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, offsetof(Vertex, color),    D3D10_INPUT_PER_VERTEX_DATA, 0 }
    };

    ID3D10InputLayout *pVertexLayout = NULL;
    hr = g_pDevice->CreateInputLayout(InputElementDescs,
                                      2,
                                      g_VS,
                                      sizeof g_VS,
                                      &pVertexLayout);
    if (FAILED(hr)) {
        return 1;
    }

    g_pDevice->IASetInputLayout(pVertexLayout);

    ID3D10PixelShader * pPixelShader;
    hr = g_pDevice->CreatePixelShader(g_PS, sizeof g_PS, &pPixelShader);
    if (FAILED(hr)) {
        return 1;
    }

    g_pDevice->VSSetShader(pVertexShader);
    g_pDevice->PSSetShader(pPixelShader);

    static const Vertex vertices[] = {
        { { -0.9f, -0.9f, 0.5f, 1.0f}, { 0.8f, 0.0f, 0.0f, 0.1f } },
        { {  0.9f, -0.9f, 0.5f, 1.0f}, { 0.0f, 0.9f, 0.0f, 0.1f } },
        { {  0.0f,  0.9f, 0.5f, 1.0f}, { 0.0f, 0.0f, 0.7f, 0.1f } },
    };

    D3D10_BUFFER_DESC BufferDesc;
    ZeroMemory(&BufferDesc, sizeof BufferDesc);
    BufferDesc.Usage = D3D10_USAGE_DYNAMIC;
    BufferDesc.ByteWidth = sizeof vertices;
    BufferDesc.BindFlags = D3D10_BIND_VERTEX_BUFFER;
    BufferDesc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE;
    BufferDesc.MiscFlags = 0;

    ID3D10Buffer *pVertexBuffer;
    hr = g_pDevice->CreateBuffer(&BufferDesc, NULL, &pVertexBuffer);
    if (FAILED(hr)) {
        return 1;
    }

    void *pMap = NULL;
    pVertexBuffer->Map(D3D10_MAP_WRITE_DISCARD, 0, &pMap);
    memcpy(pMap, vertices, sizeof vertices);
    pVertexBuffer->Unmap();

    UINT Stride = sizeof(Vertex);
    UINT Offset = 0;
    g_pDevice->IASetVertexBuffers(0, 1, &pVertexBuffer, &Stride, &Offset);
    
    D3D10_VIEWPORT ViewPort;
    ViewPort.TopLeftX = 0;
    ViewPort.TopLeftY = 0;
    ViewPort.Width = WindowWidth;
    ViewPort.Height = WindowHeight;
    ViewPort.MinDepth = 0.0f;
    ViewPort.MaxDepth = 1.0f;
    g_pDevice->RSSetViewports(1, &ViewPort);
    
    D3D10_RASTERIZER_DESC RasterizerDesc;
    ZeroMemory(&RasterizerDesc, sizeof RasterizerDesc);
    RasterizerDesc.CullMode = D3D10_CULL_NONE;
    RasterizerDesc.FillMode = D3D10_FILL_SOLID;
    RasterizerDesc.FrontCounterClockwise = true;
    RasterizerDesc.DepthClipEnable = true;
    ID3D10RasterizerState* pRasterizerState = NULL;
    hr = g_pDevice->CreateRasterizerState(&RasterizerDesc, &pRasterizerState);
    if (FAILED(hr)) {
        return 1;
    }
    g_pDevice->RSSetState(pRasterizerState);

    g_pDevice->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);
    g_pDevice->Draw(3, 0);

    g_pSwapChain->Present(0, 0);


    ID3D10Buffer *pNullBuffer = NULL;
    UINT NullStride = 0;
    UINT NullOffset = 0;
    g_pDevice->IASetVertexBuffers(0, 1, &pNullBuffer, &NullStride, &NullOffset);
    pVertexBuffer->Release();

    g_pDevice->OMSetRenderTargets(0, NULL, NULL);
    pRenderTargetView->Release();

    g_pDevice->IASetInputLayout(NULL);
    pVertexLayout->Release();

    g_pDevice->VSSetShader(NULL);
    pVertexShader->Release();

    g_pDevice->PSSetShader(NULL);
    pPixelShader->Release();

    g_pDevice->RSSetState(NULL);
    pRasterizerState->Release();

    g_pSwapChain->Release();
    g_pSwapChain = NULL;

    g_pDevice->Release();
    g_pDevice = NULL;

    g_pAdapter->Release();
    g_pAdapter = NULL;

    g_pFactory->Release();
    g_pFactory = NULL;

    DestroyWindow(hWnd);

    return 0;
}
// this is the entry point for any Windows program
// Note: It is a form of main(...), but made for Windows applications (that is, non-console applications).
// Note: I had to change the project properties->linker->system->subsystem from "Console" to "Windows" to get it to compile correctly.
int WINAPI WinMain(
   HINSTANCE h_instance,
   HINSTANCE h_prev_instance,
   LPSTR lp_cmd_line,
   int n_show_cmd)
{
   // this will be the handle for the window (hence the acronym)
   HWND handle_window;

   // this struct will hold information for the window class
   // Note: WNDCLASS is depreciated.  It was superseded by WNDCLASSEX, so use that instead.
   WNDCLASSEX wc;
   ZeroMemory(&wc, sizeof(WNDCLASSEX));

   // fill the struct with the needed information
   wc.cbSize = sizeof(WNDCLASSEX);           // tell the struct how big it is (??why doesn't it know how big itself is??)
   wc.style = CS_HREDRAW | CS_VREDRAW;       // redraw on vertical and horizontal resizing
   wc.lpfnWndProc = my_window_proc;          // this is the function that the window class calls when it gets a message from windows (keystroke, mouse movement, etc.)
   wc.hInstance = h_instance;                // the handle to our application instance
   wc.hCursor = LoadCursor(NULL, IDC_ARROW); // don't give it an application handle that stores a pointer graphic (we don't have one anyway), and give it the default mouse pointer
   //wc.hbrBackground = (HBRUSH)COLOR_WINDOW;  // give the window class's background the default window color
   wc.lpszClassName = L"WindowClass1";       // give the window class a name (when creating a window with this window class, you must specify this string exactly)

   // register the window class so that Windows can use it to create windows
   RegisterClassEx(&wc);

   // calculate the size of the window based on how big we want the client (the space within the window borders) to be
   // Note: This "adjust window rectangle" function conveniently calculates window dimensions given information about
   // the dimensions of the size and origin of the client area, the window style, and whether the window has menus or 
   // not (FALSE in this case).  The last item is some information about extended window styles for "Extended Window".
   // We are not using any such styles, so we provide NULL.
   RECT window_rectangle = { 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT };
   AdjustWindowRectEx(&window_rectangle, WS_OVERLAPPEDWINDOW, FALSE, NULL);

   // create the window on the screen
   handle_window = CreateWindowEx(
      NULL,                               // do not use any extra style options provided by "Extended Window"
      L"WindowClass1",                    // name of the window class that this window will be an instance of (must match an existing window class name)
      L"Our First Direct3D Program",      // displayed on the window's title bar
      WS_OVERLAPPEDWINDOW,                // this option specifies several standard features and make a basic window style (check out the #define for more details)
      300,                                // x-position of the window relative to the desktop
      300,                                // y-position of the window relative to the desktop
      window_rectangle.right - window_rectangle.left,    // width of the window (origin at left, increases left to right)
      window_rectangle.bottom - window_rectangle.top,    // height of the window (origin at top, increases top to bottom)
      NULL,                               // we have no parent window, so do not provide a handle to a window
      NULL,                               // we are not using menus, so do not provide a handle to a menu
      h_instance,                         // application handle determined by Windows when the program starts; identifies this window with our application
      NULL);                              // used with multiple windows, which we are not using

   // display the window on the screen
   ShowWindow(handle_window, n_show_cmd);

   // set up and initialize Direct3D
   init_d3d(handle_window);


   // enter the main loop

   // this struct holds Windows event messages
   MSG event_message = { 0 };

   // enter the loop and stay here forever
   while (true)
   {
      // check to see if any messages are waiting in the queue, and remove them from the queue if you find them
      if (PeekMessage(&event_message, NULL, 0, 0, PM_REMOVE))
      {
         // translate keystroke messages into the right format, then send them to the "window processing" function for handling
         TranslateMessage(&event_message);
         DispatchMessage(&event_message);

         // check to see if it is time to quite, and if it is, break out of the loop and return from main
         // Note: The window will not send a WM_QUIT message.  It is called when the application (in this
         // case, our code) calls the PostQuitMessage(...) function, which in turn will only be called if
         // the message was WM_DESTROY.
         // Previously, we used the return value of GetMessage(...) as the condition in the while(...) 
         // loop, and that function would return false if it got a WM_QUIT message.  Now the loop 
         // condition is always true, so we need to manually check for WM_QUIT and stop the application
         // if we see it.
         if (WM_QUIT == event_message.message)
         {
            break;
         }
      }

      // render a frame, regardless of whether a message was handled or not
      render_frame();
   }

   clean_d3d();

   // return this part (??which part??) of the WM_QUIT message to Windows
   return event_message.wParam;
}
Esempio n. 6
0
//////////////////////////////////////////////////////////////////////
// Main
//////////////////////////////////////////////////////////////////////
int main(int argc, char **argv)
{
	int i;

	fprintf(stderr, "\n%s v%s (Build %s)\n\n", bench_name, __VERSION, __BUILD);

	if(argc>1) for(i=1; i<argc; i++)
	{
		if(!stricmp(argv[i], "-checkdb"))
		{
			checkdb=1;
			fprintf(stderr, "Checking double buffering.  Watch for flashing to indicate that it is\n");
			fprintf(stderr, "not enabled.  Performance will be sub-optimal.\n");
		}
		if(!stricmp(argv[i], "-noshm"))
		{
			doshm=0;
		}
		if(!stricmp(argv[i], "-verbose"))
		{
			fbx_printwarnings(stderr);
		}
	}

	try {

	#ifdef FBXWIN32

	WNDCLASSEX wndclass;  MSG msg;
	wndclass.cbSize = sizeof(WNDCLASSEX);
	wndclass.style = CS_HREDRAW | CS_VREDRAW;
	wndclass.lpfnWndProc = WndProc;
	wndclass.cbClsExtra = 0;
	wndclass.cbWndExtra = 0;
	wndclass.hInstance = GetModuleHandle(NULL);
	wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
	wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
	wndclass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
	wndclass.lpszMenuName = NULL;
	wndclass.lpszClassName = bench_name;
	wndclass.hIconSm = LoadIcon(NULL, IDI_WINLOGO);
	tryw32(RegisterClassEx(&wndclass));
	width=GetSystemMetrics(SM_CXSCREEN);
	height=GetSystemMetrics(SM_CYSCREEN);

	#else

	if(!XInitThreads()) {fprintf(stderr, "ERROR: Could not initialize Xlib thread safety\n");  exit(1);}
	XSetErrorHandler(xhandler);
	if(!(wh.dpy=XOpenDisplay(0))) {fprintf(stderr, "Could not open display %s\n", XDisplayName(0));  exit(1);}
	width=DisplayWidth(wh.dpy, DefaultScreen(wh.dpy));
	height=DisplayHeight(wh.dpy, DefaultScreen(wh.dpy));

	#endif

	if(width<MIN_SCREEN_WIDTH && height<MIN_SCREEN_HEIGHT)
	{
		fprintf(stderr, "ERROR: Please switch to a screen resolution of at least %d x %d.\n", MIN_SCREEN_WIDTH, MIN_SCREEN_HEIGHT);
		exit(1);
	}
	width=WIDTH;
	height=HEIGHT;

	#ifdef FBXWIN32

	int bw=GetSystemMetrics(SM_CXFIXEDFRAME)*2;
	int bh=GetSystemMetrics(SM_CYFIXEDFRAME)*2+GetSystemMetrics(SM_CYCAPTION);
	tryw32(wh=CreateWindowEx(0, bench_name, bench_name, WS_OVERLAPPED |
		WS_SYSMENU | WS_CAPTION | WS_VISIBLE, 0,  0, width+bw, height+bh, NULL,
		NULL, GetModuleHandle(NULL), NULL));
	UpdateWindow(wh);
	BOOL ret;
	while(1)
	{
		if((ret=GetMessage(&msg, NULL, 0, 0))==-1) _throww32();
		else if(ret==0) break;
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}
	return (int)msg.wParam;

	#else

	XVisualInfo vtemp, *v=NULL;  int n=0;
	XSetWindowAttributes swa;
	Window root=DefaultRootWindow(wh.dpy);

	vtemp.depth=24;  vtemp.c_class=TrueColor;
	if((v=XGetVisualInfo(wh.dpy, VisualDepthMask|VisualClassMask, &vtemp, &n))!=NULL && n!=0)
	{
		swa.colormap=XCreateColormap(wh.dpy, root, v->visual, AllocNone);
		swa.border_pixel=0;
		swa.event_mask=0;
		errifnot(wh.win=XCreateWindow(wh.dpy, root, 0, 0, width, height, 0,
			v->depth, InputOutput, v->visual, CWBorderPixel|CWColormap|CWEventMask,
			&swa));
		errifnot(XMapRaised(wh.dpy, wh.win));
		XSync(wh.dpy, False);
		display();
		XDestroyWindow(wh.dpy, wh.win);
		XFree(v);  v=NULL;
	}
	else fprintf(stderr, "No RGB visuals available.  Skipping those tests.\n\n");

	vtemp.depth=8;  vtemp.c_class=PseudoColor;
	if((v=XGetVisualInfo(wh.dpy, VisualDepthMask|VisualClassMask, &vtemp, &n))!=NULL && n!=0)
	{
		swa.colormap=XCreateColormap(wh.dpy, root, v->visual, AllocAll);
		swa.border_pixel=0;
		swa.event_mask=0;
    XColor xc[32];  int i;
		errifnot(v->colormap_size==256);
		for(i=0; i<32; i++)
		{
			xc[i].red=(i<16? i*16:255)<<8;
			xc[i].green=(i<16? i*16:255-(i-16)*16)<<8;
			xc[i].blue=(i<16? 255:255-(i-16)*16)<<8;
			xc[i].flags = DoRed | DoGreen | DoBlue;
			xc[i].pixel=i;
		}
		XStoreColors(wh.dpy, swa.colormap, xc, 32);
		errifnot(wh.win=XCreateWindow(wh.dpy, root, 0, 0, width, height, 0,
			v->depth, InputOutput, v->visual, CWBorderPixel|CWColormap|CWEventMask,
			&swa));
		errifnot(XMapRaised(wh.dpy, wh.win));
		XSync(wh.dpy, False);
		display();
		XDestroyWindow(wh.dpy, wh.win);
		XFreeColormap(wh.dpy, swa.colormap);
		XFree(v);  v=NULL;
	}
	else fprintf(stderr, "No Pseudocolor visuals available.  Skipping those tests.\n\n");

	return 0;

	#endif

	} catch(rrerror &e) {fprintf(stderr, "%s\n", e.getMessage());}
}
INT WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInst, LPSTR lpszCmdLine, int nCmdShow)
{
	HWND hWnd;
	MSG lpMsg;
	WNDCLASSEX wcl;

	/* 1. Определение класса окна  */

	wcl.cbSize = sizeof (wcl);	// размер структуры WNDCLASSEX 
	wcl.style = CS_HREDRAW | CS_VREDRAW | CS_DBLCLKS;	// окно сможет получать сообщения о двойном щелчке (DBLCLK)
	wcl.lpfnWndProc = WindowProc;	// адрес оконной процедуры
	wcl.cbClsExtra = 0;		// используется Windows 
	wcl.cbWndExtra  = 0; 	// используется Windows 
	wcl.hInstance = hInst;	// дескриптор данного приложения
	wcl.hIcon = LoadIcon(NULL, IDI_APPLICATION);	// загрузка стандартной иконки
	wcl.hCursor = LoadCursor(NULL, IDC_ARROW);		// загрузка стандартного курсора
	wcl.hbrBackground = (HBRUSH) GetStockObject(WHITE_BRUSH);	//заполнение окна белым цветом			
	wcl.lpszMenuName = NULL;	// приложение не содержит меню
	wcl.lpszClassName = szClassWindow;	// имя класса окна
	wcl.hIconSm = NULL;	// отсутствие маленькой иконки для связи с классом окна


	/*  2. Регистрация класса окна  */

	if (!RegisterClassEx(&wcl))
		return 0;	// при неудачной регистрации - выход


	/*  3. Создание окна  */

	// создается окно и  переменной hWnd присваивается дескриптор окна
	hWnd = CreateWindowEx(
		0,		// расширенный стиль окна
		szClassWindow,	// имя класса окна
		TEXT("Каркас  Windows приложения"),	// заголовок окна
		/* Заголовок, рамка, позволяющая менять размеры, системное меню,
			кнопки развёртывания и свёртывания окна  */
		WS_OVERLAPPEDWINDOW,	// стиль окна
		CW_USEDEFAULT,	// х-координата левого верхнего угла окна
		CW_USEDEFAULT,	// y-координата левого верхнего угла окна
		CW_USEDEFAULT,	// ширина окна
		CW_USEDEFAULT,	// высота окна
		NULL,			// дескриптор родительского окна
		NULL,			// дескриптор меню окна
		hInst,		// идентификатор приложения, создавшего окно
		NULL);		// указатель на область данных приложения


	/* 4. Отображение окна */

	ShowWindow(hWnd, nCmdShow);
	UpdateWindow(hWnd);	// перерисовка окна


	/* 5. Запуск цикла обработки сообщений  */

	// получение очередного сообщения из очереди сообщений
	while (GetMessage(&lpMsg, NULL, 0, 0)) 
	{
		TranslateMessage(&lpMsg);	// трансляция сообщения
		DispatchMessage(&lpMsg);	// диспетчеризация сообщений
	}
	return lpMsg.wParam;
}
Esempio n. 8
0
//-----------------------------------------------------------------------------
// The engine class constructor.
//-----------------------------------------------------------------------------
Engine::Engine( EngineSetup *setup )
{
	// Indicate that the engine is not yet loaded.
	m_loaded = false;
	m_pGameStateBlock = NULL;
	m_LocalID = -1;
	m_PlayerID = -1;

	// If no setup structure was passed in, then create a default one.
	// Otehrwise, make a copy of the passed in structure.
	m_setup = new EngineSetup;
	if( setup != NULL )
		memcpy( m_setup, setup, sizeof( EngineSetup ) );

	// Prepare and register the window class.
	WNDCLASSEX wcex;
	wcex.cbSize        = sizeof( WNDCLASSEX );
	wcex.style         = CS_CLASSDC;
	wcex.lpfnWndProc   = WindowProc;
	wcex.cbClsExtra    = 0;
	wcex.cbWndExtra    = 0;
	wcex.hInstance     = m_setup->instance;
	wcex.hIcon         = LoadIcon( NULL, IDI_APPLICATION );
	wcex.hCursor       = LoadCursor( NULL, IDC_ARROW );
	wcex.hbrBackground = NULL;
	wcex.lpszMenuName  = NULL;
	wcex.lpszClassName = "WindowClass";
	wcex.hIconSm       = LoadIcon( NULL, IDI_APPLICATION );
	RegisterClassEx( &wcex );

	// Initialise the COM using multithreaded concurrency.
	CoInitializeEx( NULL, COINIT_MULTITHREADED );

	// Create the Direct3D interface.
	IDirect3D9 *d3d = Direct3DCreate9( D3D_SDK_VERSION );

	// Enumerate Direct3D device configurations on the default adapter.
	g_deviceEnumeration = new DeviceEnumeration;
	if( g_deviceEnumeration->Enumerate( d3d ) != IDOK )
	{
		SAFE_RELEASE( d3d );
		return;
	}

	// Create the window and retrieve a handle to it.
	m_window = CreateWindow( "WindowClass", m_setup->name, g_deviceEnumeration->IsWindowed() ? WS_OVERLAPPED : WS_POPUP, 0, 0, 800, 600, NULL, NULL, m_setup->instance, NULL );

	// Prepare the device presentation parameters.
	D3DPRESENT_PARAMETERS d3dpp;
	ZeroMemory( &d3dpp, sizeof( D3DPRESENT_PARAMETERS ) );
	d3dpp.BackBufferWidth = g_deviceEnumeration->GetSelectedDisplayMode()->Width;
	d3dpp.BackBufferHeight = g_deviceEnumeration->GetSelectedDisplayMode()->Height;
	d3dpp.BackBufferFormat = g_deviceEnumeration->GetSelectedDisplayMode()->Format;
	d3dpp.BackBufferCount = m_setup->totalBackBuffers;
	d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
	d3dpp.hDeviceWindow = m_window;
	d3dpp.Windowed = g_deviceEnumeration->IsWindowed();
	d3dpp.EnableAutoDepthStencil = true;
	d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
	d3dpp.FullScreen_RefreshRateInHz = g_deviceEnumeration->GetSelectedDisplayMode()->RefreshRate;
	if( g_deviceEnumeration->IsVSynced() == true )
		d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_DEFAULT;
	else
		d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;

	// Destroy the device enumeration object.
	SAFE_DELETE( g_deviceEnumeration );

	// Create the Direct3D device.
	if( FAILED( d3d->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, m_window, D3DCREATE_MIXED_VERTEXPROCESSING, &d3dpp, &m_device ) ) )
		return;

	// Release the Direct3D interface as it is no longer needed.
	SAFE_RELEASE( d3d );

	// Switch lighting off by default.
	m_device->SetRenderState( D3DRS_LIGHTING, false );

	// Set the texture filters to use anisotropic texture filtering.
	m_device->SetSamplerState ( 0, D3DSAMP_MAGFILTER, D3DTEXF_ANISOTROPIC );
	m_device->SetSamplerState ( 0, D3DSAMP_MINFILTER, D3DTEXF_ANISOTROPIC );
	m_device->SetSamplerState( 0, D3DSAMP_MIPFILTER, D3DTEXF_LINEAR );

	// Set the projection matrix.
	D3DXMATRIX projMatrix;
	D3DXMatrixPerspectiveFovLH( &projMatrix, D3DX_PI / 4, (float)d3dpp.BackBufferWidth / (float)d3dpp.BackBufferHeight, 0.1f / m_setup->scale, 1000.0f / m_setup->scale );
	m_device->SetTransform( D3DTS_PROJECTION, &projMatrix );

	// Store the display mode details.
	m_displayMode.Width = d3dpp.BackBufferWidth;
	m_displayMode.Height = d3dpp.BackBufferHeight;
	m_displayMode.RefreshRate = d3dpp.FullScreen_RefreshRateInHz;
	m_displayMode.Format = d3dpp.BackBufferFormat;

	// The swap chain always starts on the first back buffer.
	m_currentBackBuffer = 0;

	// Create the sprite interface.
	D3DXCreateSprite( m_device, &m_sprite );

	// Create the linked lists of states.
	m_states = new LinkedList< State >;
	m_currentState = NULL;

	// Create the resource managers.
	m_scriptManager = new ResourceManager< Script >;
	m_materialManager = new ResourceManager< Material >( m_setup->CreateMaterialResource );
	m_meshManager = new ResourceManager< Mesh >;

	// Create the input object.
	m_input = new Input( m_window );

	// Create the network object.
	//m_network = new Network( m_setup->guid, m_setup->HandleNetworkMessage );
	//g_hNetworkEngine = ::LoadLibrary("NetworkEngine.dll");

	//if(g_hNetworkEngine == NULL)
	//	return;

	//CREATE_NETWORKENGINE_FNC *pfunc;
	//pfunc = (CREATE_NETWORKENGINE_FNC *)::GetProcAddress( g_hNetworkEngine, "CreateNetworkEngine" );
	
	//m_network = pfunc();

	m_pNetwork = new SFNetworkEntry();

	// Create the sound system.
	m_soundSystem = new SoundSystem( m_setup->scale );

	// Create the scene manager.
	m_sceneManager = new SceneManager( m_setup->scale, m_setup->spawnerPath );


	m_pGUIManager = new GUIManager();
	m_pGUIManager->Create(m_device);

	// Seed the random number generator with the current time.
	srand( timeGetTime() );

	// Store a pointer to the engine in a global variable for easy access.
	g_engine = this;

	// Allow the application to perform any state setup now.
	if( m_setup->StateSetup != NULL )
		m_setup->StateSetup();

	SetCursor(NULL);

	// The engine is fully loaded and ready to go.
	m_loaded = true; 
	g_engine->GetDevice()->CreateStateBlock( D3DSBT_ALL, &m_pGameStateBlock ); 
}
Esempio n. 9
0
static bool d3d_construct(d3d_video_t *d3d,
      const video_info_t *info, const input_driver_t **input,
      void **input_data)
{
   unsigned full_x, full_y;

   d3d->should_resize = false;
#ifndef _XBOX
   gfx_set_dwm();
#endif

#if defined(HAVE_MENU) && defined(HAVE_OVERLAY)
   if (d3d->menu)
      free(d3d->menu);

   d3d->menu = (overlay_t*)calloc(1, sizeof(overlay_t));

   if (!d3d->menu)
      return false;

   d3d->menu->tex_coords.x = 0;
   d3d->menu->tex_coords.y = 0;
   d3d->menu->tex_coords.w = 1;
   d3d->menu->tex_coords.h = 1;
   d3d->menu->vert_coords.x = 0;
   d3d->menu->vert_coords.y = 1;
   d3d->menu->vert_coords.w = 1;
   d3d->menu->vert_coords.h = -1;
#endif

#if defined(HAVE_WINDOW) && !defined(_XBOX)
   memset(&d3d->windowClass, 0, sizeof(d3d->windowClass));
   d3d->windowClass.cbSize        = sizeof(d3d->windowClass);
   d3d->windowClass.style         = CS_HREDRAW | CS_VREDRAW;
   d3d->windowClass.lpfnWndProc   = WindowProc;
   d3d->windowClass.hInstance     = NULL;
   d3d->windowClass.hCursor       = LoadCursor(NULL, IDC_ARROW);
   d3d->windowClass.lpszClassName = "RetroArch";
   d3d->windowClass.hIcon = LoadIcon(GetModuleHandle(NULL),
         MAKEINTRESOURCE(IDI_ICON));
   d3d->windowClass.hIconSm = (HICON)LoadImage(GetModuleHandle(NULL),
         MAKEINTRESOURCE(IDI_ICON), IMAGE_ICON, 16, 16, 0);
   if (!info->fullscreen)
      d3d->windowClass.hbrBackground = (HBRUSH)COLOR_WINDOW;

   RegisterClassEx(&d3d->windowClass);
#endif

#ifdef HAVE_MONITOR
   RECT mon_rect = d3d_monitor_rect(d3d);

   bool windowed_full = g_settings.video.windowed_fullscreen;

   full_x = (windowed_full || info->width  == 0) ? 
      (mon_rect.right  - mon_rect.left) : info->width;
   full_y = (windowed_full || info->height == 0) ? 
      (mon_rect.bottom - mon_rect.top)  : info->height;
   RARCH_LOG("[D3D]: Monitor size: %dx%d.\n", 
         (int)(mon_rect.right  - mon_rect.left),
         (int)(mon_rect.bottom - mon_rect.top));
#else
   if (d3d->ctx_driver && d3d->ctx_driver->get_video_size)
      d3d->ctx_driver->get_video_size(d3d, &full_x, &full_y);
#endif
   d3d->screen_width  = info->fullscreen ? full_x : info->width;
   d3d->screen_height = info->fullscreen ? full_y : info->height;

#if defined(HAVE_WINDOW) && !defined(_XBOX)
   char buffer[128];
   unsigned win_width  = d3d->screen_width;
   unsigned win_height = d3d->screen_height;
   RECT rect = {0};

   if (!info->fullscreen)
   {
      rect.right  = d3d->screen_width;
      rect.bottom = d3d->screen_height;
      AdjustWindowRect(&rect, WS_OVERLAPPEDWINDOW, FALSE);
      win_width  = rect.right - rect.left;
      win_height = rect.bottom - rect.top;
   }

   video_monitor_get_fps(buffer, sizeof(buffer), NULL, 0);
   std::string title = buffer;
   title += " || Direct3D";

   d3d->hWnd = CreateWindowEx(0, "RetroArch", title.c_str(),
         info->fullscreen ?
         (WS_EX_TOPMOST | WS_POPUP) : WS_OVERLAPPEDWINDOW,
         info->fullscreen ? mon_rect.left : CW_USEDEFAULT,
         info->fullscreen ? mon_rect.top  : CW_USEDEFAULT,
         win_width, win_height,
         NULL, NULL, NULL, d3d);

   driver.display_type  = RARCH_DISPLAY_WIN32;
   driver.video_display = 0;
   driver.video_window  = (uintptr_t)d3d->hWnd;
#endif

   if (d3d && d3d->ctx_driver && d3d->ctx_driver->show_mouse)
      d3d->ctx_driver->show_mouse(d3d, !info->fullscreen
#ifdef HAVE_OVERLAY
      || d3d->overlays_enabled
#endif
   );

#if defined(HAVE_WINDOW) && !defined(_XBOX)
   if (!info->fullscreen && g_settings.ui.menubar_enable)
   {
	   RECT rc_temp = {0, 0, win_height, 0x7FFF};
	   SetMenu(d3d->hWnd, LoadMenu(GetModuleHandle(NULL),MAKEINTRESOURCE(IDR_MENU)));
	   SendMessage(d3d->hWnd, WM_NCCALCSIZE, FALSE, (LPARAM)&rc_temp);
	   win_height += rc_temp.top + rect.top;
	   SetWindowPos(d3d->hWnd, NULL, 0, 0, win_width, win_height, SWP_NOMOVE);
   }

   ShowWindow(d3d->hWnd, SW_RESTORE);
   UpdateWindow(d3d->hWnd);
   SetForegroundWindow(d3d->hWnd);
   SetFocus(d3d->hWnd);
#endif

#ifndef _XBOX
#ifdef HAVE_SHADERS
   /* This should only be done once here
    * to avoid set_shader() to be overridden
    * later. */
   enum rarch_shader_type type = 
      video_shader_parse_type(g_settings.video.shader_path, RARCH_SHADER_NONE);
   if (g_settings.video.shader_enable && type == RARCH_SHADER_CG)
      d3d->cg_shader = g_settings.video.shader_path;

   if (!d3d_process_shader(d3d))
      return false;
#endif
#endif

   d3d->video_info = *info;
   if (!d3d_initialize(d3d, &d3d->video_info))
      return false;

   if (input && input_data &&
      d3d->ctx_driver && d3d->ctx_driver->input_driver)
      d3d->ctx_driver->input_driver(d3d, input, input_data);

   RARCH_LOG("[D3D]: Init complete.\n");
   return true;
}
//-----------------------------------【WinMain( )函数】--------------------------------------
//	描述:Windows应用程序的入口函数,我们的程序从这里开始
//------------------------------------------------------------------------------------------------
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,LPSTR lpCmdLine, int nShowCmd)
{

	//【1】窗口创建四步曲之一:开始设计一个完整的窗口类
	WNDCLASSEX wndClass = { 0 };							//用WINDCLASSEX定义了一个窗口类
	wndClass.cbSize = sizeof( WNDCLASSEX ) ;			//设置结构体的字节数大小
	wndClass.style = CS_HREDRAW | CS_VREDRAW;	//设置窗口的样式
	wndClass.lpfnWndProc = WndProc;					//设置指向窗口过程函数的指针
	wndClass.cbClsExtra		= 0;								//窗口类的附加内存,取0就可以了
	wndClass.cbWndExtra		= 0;							//窗口的附加内存,依然取0就行了
	wndClass.hInstance = hInstance;						//指定包含窗口过程的程序的实例句柄。
	wndClass.hIcon=(HICON)::LoadImage(NULL,L"icon.ico",IMAGE_ICON,0,0,LR_DEFAULTSIZE|LR_LOADFROMFILE);  //本地加载自定义ico图标
	wndClass.hCursor = LoadCursor( NULL, IDC_ARROW );    //指定窗口类的光标句柄。
	wndClass.hbrBackground=(HBRUSH)GetStockObject(GRAY_BRUSH);  //为hbrBackground成员指定一个白色画刷句柄	
	wndClass.lpszMenuName = NULL;						//用一个以空终止的字符串,指定菜单资源的名字。
	wndClass.lpszClassName = L"ForTheDreamOfGameDevelop";		//用一个以空终止的字符串,指定窗口类的名字。

	//【2】窗口创建四步曲之二:注册窗口类
	if( !RegisterClassEx( &wndClass ) )				//设计完窗口后,需要对窗口类进行注册,这样才能创建该类型的窗口
		return -1;		

	//【3】窗口创建四步曲之三:正式创建窗口
	HWND hwnd = CreateWindow( L"ForTheDreamOfGameDevelop",WINDOW_TITLE,				//喜闻乐见的创建窗口函数CreateWindow
		WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, WINDOW_WIDTH,
		WINDOW_HEIGHT, NULL, NULL, hInstance, NULL );

	//Direct3D资源的初始化,调用失败用messagebox予以显示
	if (!(S_OK==Direct3D_Init (hwnd,hInstance)))
	{
		MessageBox(hwnd, _T("Direct3D初始化失败~!"), _T("浅墨的消息窗口"), 0); //使用MessageBox函数,创建一个消息窗口 
	}

	//【4】窗口创建四步曲之四:窗口的移动、显示与更新
	MoveWindow(hwnd,250,80,WINDOW_WIDTH,WINDOW_HEIGHT,true);		//调整窗口显示时的位置,使窗口左上角位于(250,80)处
	ShowWindow( hwnd, nShowCmd );    //调用ShowWindow函数来显示窗口
	UpdateWindow(hwnd);						//对窗口进行更新,就像我们买了新房子要装修一样

	//进行DirectInput类的初始化
	g_pDInput = new DInputClass();
	g_pDInput->Init(hwnd,hInstance,DISCL_FOREGROUND | DISCL_NONEXCLUSIVE,DISCL_FOREGROUND | DISCL_NONEXCLUSIVE);
	PlaySound(L"偽りの饗宴.wav", NULL, SND_FILENAME | SND_ASYNC|SND_LOOP); //循环播放背景音乐 

	//【5】消息循环过程
	MSG msg = { 0 };  //初始化msg
	while( msg.message != WM_QUIT )			//使用while循环
	{
		if( PeekMessage( &msg, 0, 0, 0, PM_REMOVE ) )   //查看应用程序消息队列,有消息时将队列中的消息派发出去。
		{
			TranslateMessage( &msg );		//将虚拟键消息转换为字符消息
			DispatchMessage( &msg );		//该函数分发一个消息给窗口程序。
		}
		else
		{
			Direct3D_Update(hwnd);			//调用更新函数,进行画面的更新
			Direct3D_Render(hwnd);			//调用渲染函数,进行画面的渲染	
		}
	}
	//【6】窗口类的注销
	UnregisterClass(L"ForTheDreamOfGameDevelop", wndClass.hInstance);  //程序准备结束,注销窗口类
	return 0;  
}
Esempio n. 11
0
//-----------------------------------WinMain-----------------------------------------
//	Entry point for our windows application
//-----------------------------------------------------------------------------------
int WINAPI WinMain(	HINSTANCE hinstance,
					          HINSTANCE hprevinstance,
					          LPSTR lpcmdline,
					          int ncmdshow)
{

	WNDCLASSEX winclass; 
	HWND	   hWnd;	 
	MSG		   msg;		 

	// first fill in the window class stucture
	winclass.cbSize       = sizeof(WNDCLASSEX);
	winclass.style			  = CS_HREDRAW | CS_VREDRAW;
	winclass.lpfnWndProc	= WindowProc;
	winclass.cbClsExtra		= 0;
	winclass.cbWndExtra		= 0;
	winclass.hInstance		= hinstance;
	winclass.hIcon			  = LoadIcon(NULL, IDI_APPLICATION);
	winclass.hCursor		  = LoadCursor(NULL, IDC_ARROW); 
	winclass.hbrBackground= NULL; 
	winclass.lpszMenuName	= NULL;
	winclass.lpszClassName= szWindowClassName;
	winclass.hIconSm      = LoadIcon(NULL, IDI_APPLICATION);


	// register the window class
	if (!RegisterClassEx(&winclass))
	{
		MessageBoxA(NULL, "Error Registering Class!", "Error", 0);
    return 0;
	}

	// create a window which cannot be resized
	if (!(hWnd = CreateWindowEx(NULL,									
								szWindowClassName,						
								szApplicationName,						
								WS_OVERLAPPED | WS_VISIBLE | WS_CAPTION | WS_SYSMENU,
					 			GetSystemMetrics(SM_CXSCREEN)/2 - WINDOW_WIDTH/2,
                GetSystemMetrics(SM_CYSCREEN)/2 - WINDOW_HEIGHT/2,								
								WINDOW_WIDTH,
                WINDOW_HEIGHT,				
								NULL,									
								NULL,								
								hinstance,								
								NULL)))	
	{
    MessageBoxA(NULL, "Error Creating Window!", "Error", 0);
		return 0;
	}
	
	// Show the window
	ShowWindow(hWnd, SW_SHOWDEFAULT );
	UpdateWindow(hWnd);

	//create a timer
	CTimer timer(FRAMES_PER_SECOND);

	//start the timer
	timer.Start();

	// Enter the message loop
	bool bDone = false;

	while(!bDone)
	{
					
		while( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) ) 
		{
			if( msg.message == WM_QUIT ) 
			{
				// Stop loop if it's a quit message
				bDone = true;
			} 

			else 
			{
				TranslateMessage( &msg );
				DispatchMessage( &msg );
			}
		}
							
		if (timer.ReadyForNextFrame())
		{	
		  if(!g_pController->Update(timer.GetTimeElapsed()))
			{
				//we have a problem, end app
				bDone = true;
			}

			//this will call WM_PAINT which will render our scene
			InvalidateRect(hWnd, NULL, TRUE);
			UpdateWindow(hWnd);
    }					
					
	}//end while
	

  // Clean up everything and exit the app
  Cleanup();
  UnregisterClass( szWindowClassName, winclass.hInstance );
	
	return 0;

} // end WinMain
Esempio n. 12
0
void Window::build() {
	WNDCLASSEX wcx;

//Build the properties of the main window
	wcx.cbClsExtra = 0;
	wcx.cbSize = sizeof(wcx);
	wcx.cbWndExtra = 0;
	wcx.hbrBackground = static_cast<HBRUSH>(GetStockObject(this->bkgColor));
	wcx.hCursor = LoadCursor(NULL, IDC_ARROW);
	wcx.hIcon = NULL;
	wcx.hIconSm = NULL;
	wcx.hInstance = this->hInstance;
	wcx.lpfnWndProc = this->eventHandler;
	wcx.lpszClassName = this->name;
	wcx.lpszMenuName = NULL;
	wcx.style = CS_HREDRAW | CS_VREDRAW;

//Register the window class
	if (RegisterClassEx(&wcx) == 0) {
		//throw new Window_Error("FATAL ERROR: Could not register the window");
	}

//Create the style of the window
	DWORD style = this->fullScreen ? WS_EX_TOPMOST | WS_POPUP | WS_VISIBLE : WS_OVERLAPPEDWINDOW;

//Create the winddow
	*hwnd = CreateWindow(
		this->name,
		this->title,
		style,
		CW_USEDEFAULT,
		CW_USEDEFAULT,
		this->width,
		this->height,
		static_cast<HWND>(NULL),
		static_cast<HMENU>(NULL),
		this->hInstance,
		static_cast<LPVOID>(NULL)
	);

	if (!this->hwnd) {
		//throw new Window_Error("FATAL ERROR: Could not create the window");
	}

//Adjust the size of the window to match the given dimensions
	if(!this->fullScreen) {
        RECT clientRect;
        GetClientRect(*hwnd, &clientRect);

        MoveWindow(
			*hwnd,
			0,
			0,
			this->width + (this->width - clientRect.right),
			this->height +(this->height - clientRect.bottom),
			TRUE
		);
    }

//Show the window
    ShowWindow(*hwnd, this->nCmdShow);
}
Esempio n. 13
0
//----------------------------------------------------------------------------------------------------//
// This is the message handler function for the main dialog box.  It is responsible for handling
// any interaction with it's controls and for updating the trajectory views that we'll be displaying.
//----------------------------------------------------------------------------------------------------//
LRESULT CALLBACK DemoDlgProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
//----------------------------------------------------------------------------------------------------//
{
	static	HWND	hTopView;
	static	HWND	hSideView;
	WNDCLASSEX		wclass;
	char			str[16];
	int				status;
	RECT			r;
	HDC				hdc;


	switch (message) {
		// Initialize the dialog box here:
		case WM_INITDIALOG:
			// setup a child window class so we can create a couple
			// of windows to draw the two trajectory views on
			wclass.cbSize				=	sizeof(wclass);
			wclass.style				=	CS_HREDRAW | CS_VREDRAW;
			wclass.lpfnWndProc			=	DefaultWndProc;
			wclass.cbClsExtra			=	0;
			wclass.cbWndExtra			=	0;
			wclass.hInstance			=	hinst;
			wclass.hIcon				=	NULL;
			wclass.hCursor				=   NULL;
			wclass.hbrBackground		=	(HBRUSH) CreateSolidBrush(RGB(0,0,0));
			wclass.lpszMenuName			=	NULL;
			wclass.lpszClassName		=	"ViewClass";
			wclass.hIconSm				=	NULL;

			RegisterClassEx(&wclass);

			// Now go ahead and create a child window for the top view
			hTopView = CreateWindowEx(	0L,
									"ViewClass",
									NULL,
									WS_CHILD | WS_VISIBLE | WS_BORDER,
									150,
									10,
									500,
									200,
									hDlg,
									NULL,
									hinst,
									NULL);

			// Tag the window with our identifier, MYTOPVIEW, so that we
			// can distinguish it from the side view window when it's time
			// to draw in the window.
			SetWindowLong(hTopView, GWL_USERDATA, MYTOPVIEW);

			// Show the window
			ShowWindow(hTopView, SW_SHOW);
			UpdateWindow(hTopView);

			// Now go ahead and create a child window for the side view
			hSideView = CreateWindowEx(	0L,
									"ViewClass",
									NULL,
									WS_CHILD | WS_VISIBLE | WS_BORDER,
									150,
									10+10+200,
									500,
									200,
									hDlg,
									NULL,
									hinst,
									NULL);

			// Tag the window with our identifier, MYSIDEVIEW, so that we
			// can distinguish it from the top view window when it's time
			// to draw in the window.
			SetWindowLong(hSideView, GWL_USERDATA, MYSIDEVIEW);

			// Show the window
			ShowWindow(hSideView, SW_SHOW);
			UpdateWindow(hSideView);

			// Now initialize all of the edit controls on the dialog box with our
			// default values for each variable.

			// Set default values for all variables
			InitializeVariables();

			// Now convert each variable value to a string and
			// set the appropriate edit control
			sprintf( str, "%f", Vm );
			SetDlgItemText(hDlg, IDC_VM, str);

			sprintf( str, "%f", Alpha );
			SetDlgItemText(hDlg, IDC_ALPHA, str);

			sprintf( str, "%f", Gamma );
			SetDlgItemText(hDlg, IDC_GAMMA, str);

			sprintf( str, "%f", L );
			SetDlgItemText(hDlg, IDC_L, str);

			sprintf( str, "%f", Yb );
			SetDlgItemText(hDlg, IDC_YB, str);

			sprintf( str, "%f", X );
			SetDlgItemText(hDlg, IDC_X, str);

			sprintf( str, "%f", Y );
			SetDlgItemText(hDlg, IDC_Y, str);

			sprintf( str, "%f", Z );
			SetDlgItemText(hDlg, IDC_Z, str);

			sprintf( str, "%f", Length );
			SetDlgItemText(hDlg, IDC_LENGTH, str);

			sprintf( str, "%f", Width );
			SetDlgItemText(hDlg, IDC_WIDTH, str);

			sprintf( str, "%f", Height );
			SetDlgItemText(hDlg, IDC_HEIGHT, str);

			break;

		// handle the dialog controls here:
		case WM_COMMAND:
			switch( LOWORD( wParam) )
			{
				case IDC_REFRESH:
					// update the variables with
					// the values shown in the edit controls
					GetDlgItemText(hDlg, IDC_VM, str, 15);
					Vm = atof(str);

					GetDlgItemText(hDlg, IDC_ALPHA, str, 15);
					Alpha = atof(str);

					GetDlgItemText(hDlg, IDC_GAMMA, str, 15);
					Gamma = atof(str);

					GetDlgItemText(hDlg, IDC_L, str, 15);
					L  = atof(str);

					GetDlgItemText(hDlg, IDC_YB, str, 15);
					Yb = atof(str);

					GetDlgItemText(hDlg, IDC_X, str, 15);
					X = atof(str);

					GetDlgItemText(hDlg, IDC_Y, str, 15);
					Y = atof(str);

					GetDlgItemText(hDlg, IDC_Z, str, 15);
					Z = atof(str);

					GetDlgItemText(hDlg, IDC_LENGTH, str, 15);
					Length = atof(str);

					GetDlgItemText(hDlg, IDC_WIDTH, str, 15);
					Width = atof(str);

					GetDlgItemText(hDlg, IDC_HEIGHT, str, 15);
					Height = atof(str);

					// re-initialize the time and position of the shell
					time = 0;
					s.i = 0;
					s.j = 0;
					s.k = 0;

					// Repaint the views
					hdc = GetDC(hTopView);
					GetClientRect(hTopView, &r);
					DrawTopView(hdc, &r);
					ReleaseDC(hTopView, hdc);

					hdc = GetDC(hSideView);
					GetClientRect(hSideView, &r);
					DrawSideView(hdc, &r);
					ReleaseDC(hSideView, hdc);
					break;

				case IDC_FIRE:
					// update the variables with
					// the values shown in the edit controls
					GetDlgItemText(hDlg, IDC_VM, str, 15);
					Vm = atof(str);

					GetDlgItemText(hDlg, IDC_ALPHA, str, 15);
					Alpha = atof(str);

					GetDlgItemText(hDlg, IDC_GAMMA, str, 15);
					Gamma = atof(str);

					GetDlgItemText(hDlg, IDC_L, str, 15);
					L  = atof(str);

					GetDlgItemText(hDlg, IDC_YB, str, 15);
					Yb = atof(str);

					GetDlgItemText(hDlg, IDC_X, str, 15);
					X = atof(str);

					GetDlgItemText(hDlg, IDC_Y, str, 15);
					Y = atof(str);

					GetDlgItemText(hDlg, IDC_Z, str, 15);
					Z = atof(str);

					GetDlgItemText(hDlg, IDC_LENGTH, str, 15);
					Length = atof(str);

					GetDlgItemText(hDlg, IDC_WIDTH, str, 15);
					Width = atof(str);

					GetDlgItemText(hDlg, IDC_HEIGHT, str, 15);
					Height = atof(str);

					// initialize the time and status variables
					status = 0;
					time = 0;
					// start stepping through time for the sim.
					// until the target is hit, the shell hits
					// the ground, or the sim. times out.
					while(status == 0)
					{
						// do the next time step
						status = DoSimulation();

						// update the views
						hdc = GetDC(hTopView);
						GetClientRect(hTopView, &r);
						DrawTopView(hdc, &r);
						ReleaseDC(hTopView, hdc);

						hdc = GetDC(hSideView);
						GetClientRect(hSideView, &r);
						DrawSideView(hdc, &r);
						ReleaseDC(hSideView, hdc);
					}

					// Report results
					if (status == 1)
						MessageBox(NULL, "Direct Hit", "Score!", MB_OK);

					if (status == 2)
						MessageBox(NULL, "Missed Target", "No Score.", MB_OK);

					if (status == 3)
						MessageBox(NULL, "Timed Out", "Error", MB_OK);
					break;

				case ID_CLOSE:
					// clean up the child windows and close the dialog box
					DestroyWindow(hTopView);
					DestroyWindow(hSideView);
					EndDialog(hDlg, 1);
					break;

				case IDCANCEL:
					// clean up the child windows and close the dialog box
					DestroyWindow(hTopView);
					DestroyWindow(hSideView);
					EndDialog(hDlg, 0);
					break;
			}
			break;

		default:
			return( FALSE );
	}
    return ( TRUE );
}
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow )
{
	Gdiplus::GdiplusStartupInput gdiplusStartupInput;
	ULONG_PTR gdiplusToken;

	unsigned char fail_type = 0;

	// Initialize GDI+.
	Gdiplus::GdiplusStartup( &gdiplusToken, &gdiplusStartupInput, NULL );

	// Blocks our reading thread and various GUI operations.
	InitializeCriticalSection( &pe_cs );

	// Get the default message system font.
	NONCLIENTMETRICS ncm = { NULL };
	ncm.cbSize = sizeof( NONCLIENTMETRICS );
	SystemParametersInfo( SPI_GETNONCLIENTMETRICS, sizeof( NONCLIENTMETRICS ), &ncm, 0 );

	// Set our global font to the LOGFONT value obtained from the system.
	hFont = CreateFontIndirect( &ncm.lfMessageFont );

	// Get the row height for our listview control.
	TEXTMETRIC tm;
	HDC hDC = GetDC( NULL );
	HFONT ohf = ( HFONT )SelectObject( hDC, hFont );
	GetTextMetricsW( hDC, &tm );
	SelectObject( hDC, ohf );	// Reset old font.
	ReleaseDC( NULL, hDC );

	row_height = tm.tmHeight + tm.tmExternalLeading + 5;

	int icon_height = GetSystemMetrics( SM_CYSMICON ) + 2;
	if ( row_height < icon_height )
	{
		row_height = icon_height;
	}

	// Get the system icon for each of the three file types.
	SHFILEINFOA shfi = { NULL }; 
	SHGetFileInfoA( ".bmp", FILE_ATTRIBUTE_NORMAL, &shfi, sizeof( shfi ), SHGFI_ICON | SHGFI_SMALLICON | SHGFI_USEFILEATTRIBUTES );
	hIcon_bmp = shfi.hIcon;
	SHGetFileInfoA( ".png", FILE_ATTRIBUTE_NORMAL, &shfi, sizeof( shfi ), SHGFI_ICON | SHGFI_SMALLICON | SHGFI_USEFILEATTRIBUTES );
	hIcon_png = shfi.hIcon;
	SHGetFileInfoA( ".jpg", FILE_ATTRIBUTE_NORMAL, &shfi, sizeof( shfi ), SHGFI_ICON | SHGFI_SMALLICON | SHGFI_USEFILEATTRIBUTES );
	hIcon_jpg = shfi.hIcon;

	// Initialize our window class.
	WNDCLASSEX wcex;
	wcex.cbSize			= sizeof( WNDCLASSEX );
	wcex.style          = CS_VREDRAW | CS_HREDRAW;
	wcex.lpfnWndProc    = MainWndProc;
	wcex.cbClsExtra     = 0;
	wcex.cbWndExtra     = 0;
	wcex.hInstance      = hInstance;
	wcex.hIcon          = LoadIcon( hInstance, MAKEINTRESOURCE( IDI_ICON ) );
	wcex.hCursor        = LoadCursor( NULL, IDC_ARROW );
	wcex.hbrBackground  = ( HBRUSH )( COLOR_WINDOW );
	wcex.lpszMenuName   = NULL;
	wcex.lpszClassName  = L"thumbcache";
	wcex.hIconSm        = LoadIcon( wcex.hInstance, MAKEINTRESOURCE( IDI_APPLICATION ) );

	if ( !RegisterClassEx( &wcex ) )
	{
		fail_type = 1;
		goto CLEANUP;
	}

	wcex.lpfnWndProc    = ImageWndProc;
	wcex.lpszClassName  = L"image";

	if ( !RegisterClassEx( &wcex ) )
	{
		fail_type = 1;
		goto CLEANUP;
	}

	wcex.lpfnWndProc    = ScanWndProc;
	wcex.lpszClassName  = L"scan";

	if ( !RegisterClassEx( &wcex ) )
	{
		fail_type = 1;
		goto CLEANUP;
	}

	wcex.lpfnWndProc    = InfoWndProc;
	wcex.lpszClassName  = L"info";

	if ( !RegisterClassEx( &wcex ) )
	{
		fail_type = 1;
		goto CLEANUP;
	}

	wcex.lpfnWndProc    = PropertyWndProc;
	wcex.lpszClassName  = L"property";

	if ( !RegisterClassEx( &wcex ) )
	{
		fail_type = 1;
		goto CLEANUP;
	}

	g_hWnd_main = CreateWindow( L"thumbcache", PROGRAM_CAPTION, WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN, ( ( GetSystemMetrics( SM_CXSCREEN ) - MIN_WIDTH ) / 2 ), ( ( GetSystemMetrics( SM_CYSCREEN ) - MIN_HEIGHT ) / 2 ), MIN_WIDTH, MIN_HEIGHT, NULL, NULL, NULL, NULL );

	if ( !g_hWnd_main )
	{
		fail_type = 2;
		goto CLEANUP;
	}

	g_hWnd_image = CreateWindow( L"image", PROGRAM_CAPTION, WS_OVERLAPPEDWINDOW, ( ( GetSystemMetrics( SM_CXSCREEN ) - MIN_WIDTH ) / 2 ), ( ( GetSystemMetrics( SM_CYSCREEN ) - MIN_HEIGHT ) / 2 ), MIN_HEIGHT, MIN_HEIGHT, NULL, NULL, NULL, NULL );

	if ( !g_hWnd_image )
	{
		fail_type = 2;
		goto CLEANUP;
	}

	g_hWnd_scan = CreateWindow( L"scan", L"Map File Paths to Cache Entry Hashes", WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_CLIPCHILDREN, ( ( GetSystemMetrics( SM_CXSCREEN ) - MIN_WIDTH ) / 2 ), ( ( GetSystemMetrics( SM_CYSCREEN ) - ( MIN_HEIGHT - 115 ) ) / 2 ), MIN_WIDTH, ( MIN_HEIGHT - 115 ), g_hWnd_main, NULL, NULL, NULL );

	if ( !g_hWnd_scan )
	{
		fail_type = 2;
		goto CLEANUP;
	}

	g_hWnd_info = CreateWindow( L"info", L"Extended Information", WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN, ( ( GetSystemMetrics( SM_CXSCREEN ) - MIN_WIDTH ) / 2 ), ( ( GetSystemMetrics( SM_CYSCREEN ) - MIN_WIDTH ) / 2 ), MIN_WIDTH, MIN_WIDTH, NULL, NULL, NULL, NULL );

	if ( !g_hWnd_info )
	{
		fail_type = 2;
		goto CLEANUP;
	}

	g_hWnd_property = CreateWindow( L"property", L"Property Value", WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN, ( ( GetSystemMetrics( SM_CXSCREEN ) - MIN_HEIGHT ) / 2 ), ( ( GetSystemMetrics( SM_CYSCREEN ) - MIN_HEIGHT ) / 2 ), MIN_HEIGHT, MIN_HEIGHT, NULL, NULL, NULL, NULL );

	if ( !g_hWnd_property )
	{
		fail_type = 2;
		goto CLEANUP;
	}

	// See if we have any command-line parameters
	if ( lpCmdLine != NULL && lpCmdLine[ 0 ] != NULL )
	{
		// Count the number of parameters and split them into an array.
		int argCount = 0;
		LPWSTR *szArgList = CommandLineToArgvW( GetCommandLine(), &argCount );
		if ( szArgList != NULL )
		{
			// The first parameter is the path to the executable. Ignore it.
			if ( argCount > 1 )
			{
				// Allocate enough space to hold each parameter. They should all be full paths.
				pathinfo *pi = ( pathinfo * )malloc( sizeof( pathinfo ) );
				pi->type = 0;
				pi->offset = 0;
				pi->output_path = NULL;
				pi->filepath = ( wchar_t * )malloc( sizeof( wchar_t ) * ( ( MAX_PATH * ( argCount - 1 ) ) + 1 ) );
				wmemset( pi->filepath, 0, ( ( MAX_PATH * ( argCount - 1 ) ) + 1 ) );

				cmd_line = 1;	// Open the database(s) from the command-line.

				int filepath_offset = 0;
				for ( int i = 1; i < argCount; ++i )
				{
					int filepath_length = wcslen( szArgList[ i ] );

					// See if it's an output parameter.
					if ( filepath_length > 1 && szArgList[ i ][ 0 ] == L'-' && ( szArgList[ i ][ 1 ] == L'o' || szArgList[ i ][ 1 ] == L'O' ) )
					{
						// See if the next parameter exists. We'll assume it's the output directory.
						if ( i + 1 < argCount )
						{
							if ( pi->output_path != NULL )
							{
								free( pi->output_path );
							}

							pi->output_path = _wcsdup( szArgList[ ++i ] );
							pi->type = 0;

							cmd_line = 2;	// Save the database(s) from the command-line. Do not display the main window or any prompts.
						}
					}
					else if ( filepath_length > 1 && szArgList[ i ][ 0 ] == L'-' && ( szArgList[ i ][ 1 ] == L'c' || szArgList[ i ][ 1 ] == L'C' ) )
					{
						// See if the next parameter exists. We'll assume it's the output directory.
						if ( i + 1 < argCount )
						{
							if ( pi->output_path != NULL )
							{
								free( pi->output_path );
							}

							pi->output_path = _wcsdup( szArgList[ ++i ] );
							pi->type = 1;

							cmd_line = 2;	// Save the database(s) from the command-line. Do not display the main window or any prompts.
						}
					}
					else if ( filepath_length > 1 && szArgList[ i ][ 0 ] == L'-' && ( szArgList[ i ][ 1 ] == L'z' || szArgList[ i ][ 1 ] == L'Z' ) )
					{
						hide_blank_entries = true;

						// Put a check next to the menu item. g_hMenu is created in g_hWnd_main.
						CheckMenuItem( g_hMenu, MENU_HIDE_BLANK, MF_CHECKED );
					}
					else	// Copy the paths into the NULL separated filepath.
					{
						// If the user typed a relative path, get the full path.
						wchar_t full_path[ MAX_PATH ] = { 0 };
						DWORD full_path_length = min( GetFullPathName( szArgList[ i ], MAX_PATH, full_path, NULL ), MAX_PATH );

						wmemcpy_s( pi->filepath + filepath_offset, ( ( MAX_PATH * ( argCount - 1 ) ) + 1 ) - filepath_offset, full_path, full_path_length + 1 );
						filepath_offset += ( full_path_length + 1 );
					}
				}

				// Only read the database if there's a file to open.
				if ( pi->filepath[ 0 ] != NULL )
				{
					// filepath will be freed in the thread.
					CloseHandle( ( HANDLE )_beginthreadex( NULL, 0, &read_thumbcache, ( void * )pi, 0, NULL ) );
				}
				else
				{
					// Cleanup our parameters structure and exit the program.
					free( pi->output_path );
					free( pi->filepath );
					free( pi );

					cmd_line = -1;

					SendMessage( g_hWnd_main, WM_DESTROY_ALT, 0, 0 );
				}
			}

			// Free the parameter list.
			LocalFree( szArgList );
		}
	}

	if ( cmd_line == 0 || cmd_line == 1 )
	{
		ShowWindow( g_hWnd_main, SW_SHOW );
	}

	// Main message loop:
	MSG msg;
	while ( GetMessage( &msg, NULL, 0, 0 ) > 0 )
	{
		if ( g_hWnd_active == NULL || !IsDialogMessage( g_hWnd_active, &msg ) )	// Checks tab stops.
		{
			TranslateMessage( &msg );
			DispatchMessage( &msg );
		}
	}

CLEANUP:

	// Destroy our icons.
	DestroyIcon( hIcon_jpg );
	DestroyIcon( hIcon_png );
	DestroyIcon( hIcon_bmp );

	// Delete our font.
	DeleteObject( hFont );

	// Delete our critical section.
	DeleteCriticalSection( &pe_cs );

	// Shutdown GDI+
	Gdiplus::GdiplusShutdown( gdiplusToken );

	// Unload the modules if they were initialized.
	UnInitializeMsSrch();
	UnInitializeMsSCB();

	if ( fail_type == 1 )
	{
		MessageBoxA( NULL, "Call to RegisterClassEx failed!", PROGRAM_CAPTION_A, MB_ICONWARNING );
	}
	else if ( fail_type == 2 )
	{
		MessageBoxA( NULL, "Call to CreateWindow failed!", PROGRAM_CAPTION_A, MB_ICONWARNING );
	}

	return ( int )msg.wParam;
}
int PASCAL WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR szCmdLine, int nCmdShow)
{
  WNDCLASSEX wcex;
  MSG        Msg;
  HWND       hWnd;

  // Initialize the COM system
  CoInitialize(NULL);

  // Create the window class here and register it
  wcex.cbSize        = sizeof(wcex);
  wcex.style         = CS_CLASSDC;
  wcex.lpfnWndProc   = WindowProc;
  wcex.cbClsExtra    = 0;
  wcex.cbWndExtra    = 0;
  wcex.hInstance     = hInst;
  wcex.hIcon         = LoadIcon(NULL, IDI_APPLICATION);
  wcex.hCursor       = LoadCursor(NULL, IDC_ARROW);
  wcex.hbrBackground = NULL;
  wcex.lpszMenuName  = NULL;
  wcex.lpszClassName = g_szClass;
  wcex.hIconSm       = LoadIcon(NULL, IDI_APPLICATION);
  if(!RegisterClassEx(&wcex))
    return FALSE;

  // Create the main window
  hWnd = CreateWindow(g_szClass, g_szCaption,
              WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX,
              0, 0, 640, 480,
              NULL, NULL, hInst, NULL);
  if(!hWnd)
    return FALSE;
  ShowWindow(hWnd, SW_NORMAL);
  UpdateWindow(hWnd);

  // Call init function and enter message pump
  if(DoInit(hWnd) == TRUE) {

    // Start message pump, waiting for user to exit
    ZeroMemory(&Msg, sizeof(MSG));
    while(Msg.message != WM_QUIT) {
      if(PeekMessage(&Msg, NULL, 0, 0, PM_REMOVE)) {
        TranslateMessage(&Msg);
        DispatchMessage(&Msg);
      }

      // Render a single frame
      DoFrame();
    }
  }

  // Call shutdown
  DoShutdown();

  // Unregister the window class
  UnregisterClass(g_szClass, hInst);

  // Shut down the COM system
  CoUninitialize();

  return 0;
}
Esempio n. 16
0
int WINAPI wWinMain ( HINSTANCE hInstance , HINSTANCE prevInstance , LPWSTR cmdLine , int cmdShow )
{
	UNREFERENCED_PARAMETER ( prevInstance );
	UNREFERENCED_PARAMETER ( cmdLine );

	WNDCLASSEX wndClass = { 0 };
	wndClass.cbSize = sizeof ( WNDCLASSEX );
	wndClass.style = CS_HREDRAW | CS_VREDRAW;
	wndClass.lpfnWndProc = WndProc;
	wndClass.hInstance = hInstance;
	wndClass.hCursor = LoadCursor ( NULL , IDC_ARROW );
	wndClass.hbrBackground = ( HBRUSH ) ( COLOR_WINDOW + 1 );
	wndClass.lpszMenuName = NULL;
	wndClass.lpszClassName = "DX11BookWindowClass";
	
	if( !RegisterClassEx( &wndClass ))
	{
		return -1;
	}

	RECT rc = { 0 , 0 , 640 , 480 };
	AdjustWindowRect( &rc , WS_OVERLAPPEDWINDOW , FALSE );

	HWND hwnd = CreateWindowEx ( WS_EX_OVERLAPPEDWINDOW, "DX11BookWindowClass" , "Blank Direct3D 11 Window" , WS_OVERLAPPEDWINDOW ,
		CW_USEDEFAULT , CW_USEDEFAULT , rc.right - rc.left , rc.bottom - rc.top , NULL , NULL , hInstance , NULL );

/*
	HWND hwnd = CreateWindowA ( "DX11BookWindowClass" , "Blank Direct 3D 11 Window" , WS_OVERLAPPEDWINDOW , CW_USEDEFAULT , CW_USEDEFAULT , rc.right - rc.left , 
		rc.bottom - rc.top , NULL , NULL , hInstance , NULL );
*/


	if( !hwnd )
		return -1;

	ShowWindow( hwnd , cmdShow );

	std :: auto_ptr< Dx11DemoBase >demo ( new CameraDemo());


	//Demo Initialize
	bool result = demo ->Initialize ( hInstance , hwnd );

	//Error reporting if there is an issue 
	if( result == false )
		return -1;
	MSG msg = { 0 };

	while ( msg.message != WM_QUIT )
	{
		if( PeekMessage ( &msg , 0 , 0 , 0 , PM_REMOVE ))
		{
			TranslateMessage( & msg );
			DispatchMessage ( & msg );
		}
		else 
		{
			//Update and draw
			demo ->Update (0.0f);
			demo ->Render ( );
		}
	}

	//demo shutdown
	demo ->Shutdown( );

	return static_cast<int>( msg.wParam );


}
Esempio n. 17
0
//-----------------------------------------------------------------------------------------------
void CreateOpenGLWindow(HINSTANCE applicationInstanceHandle)
{
	// Define a window class
	WNDCLASSEX windowClassDescription;
	memset(&windowClassDescription, 0, sizeof(windowClassDescription));
	windowClassDescription.cbSize = sizeof(windowClassDescription);
	windowClassDescription.style = CS_OWNDC; // Redraw on move, request own Display Context
	windowClassDescription.lpfnWndProc = static_cast<WNDPROC>(WindowsMessageHandlingProcedure); // Assign a win32 message-handling function
	windowClassDescription.hInstance = GetModuleHandle(NULL);
	windowClassDescription.hIcon = NULL;
	windowClassDescription.hCursor = NULL;
	windowClassDescription.lpszClassName = TEXT("Simple Window Class");
	RegisterClassEx(&windowClassDescription);

	const DWORD windowStyleFlags = WS_CAPTION | WS_BORDER | WS_THICKFRAME | WS_SYSMENU | WS_OVERLAPPED;
	const DWORD windowStyleExFlags = WS_EX_APPWINDOW;

	RECT desktopRect;
	HWND desktopWindowHandle = GetDesktopWindow();
	GetClientRect(desktopWindowHandle, &desktopRect);

	RECT windowRect = { OFFSET_FROM_WINDOWS_DESKTOP, OFFSET_FROM_WINDOWS_DESKTOP, OFFSET_FROM_WINDOWS_DESKTOP + WINDOW_PHYSICAL_WIDTH, OFFSET_FROM_WINDOWS_DESKTOP + WINDOW_PHYSICAL_HEIGHT };
	AdjustWindowRectEx(&windowRect, windowStyleFlags, FALSE, windowStyleExFlags);

	WCHAR windowTitle[1024];
	MultiByteToWideChar(GetACP(), 0, APP_NAME, -1, windowTitle, sizeof(windowTitle) / sizeof(windowTitle[0]));
	g_hWnd = CreateWindowEx(
		windowStyleExFlags,
		windowClassDescription.lpszClassName,
		windowTitle,
		windowStyleFlags,
		windowRect.left,
		windowRect.top,
		windowRect.right - windowRect.left,
		windowRect.bottom - windowRect.top,
		NULL,
		NULL,
		applicationInstanceHandle,
		NULL);

	ShowWindow(g_hWnd, SW_SHOW);
	SetForegroundWindow(g_hWnd);
	SetFocus(g_hWnd);

	g_displayDeviceContext = GetDC(g_hWnd);

	HCURSOR cursor = LoadCursor(NULL, IDC_ARROW);
	SetCursor(cursor);

	PIXELFORMATDESCRIPTOR pixelFormatDescriptor;
	memset(&pixelFormatDescriptor, 0, sizeof(pixelFormatDescriptor));
	pixelFormatDescriptor.nSize = sizeof(pixelFormatDescriptor);
	pixelFormatDescriptor.nVersion = 1;
	pixelFormatDescriptor.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
	pixelFormatDescriptor.iPixelType = PFD_TYPE_RGBA;
	pixelFormatDescriptor.cColorBits = 24;
	pixelFormatDescriptor.cDepthBits = 24;
	pixelFormatDescriptor.cAccumBits = 0;
	pixelFormatDescriptor.cStencilBits = 8;

	int pixelFormatCode = ChoosePixelFormat(g_displayDeviceContext, &pixelFormatDescriptor);
	SetPixelFormat(g_displayDeviceContext, pixelFormatCode, &pixelFormatDescriptor);
	g_openGLRenderingContext = wglCreateContext(g_displayDeviceContext);
	wglMakeCurrent(g_displayDeviceContext, g_openGLRenderingContext);

	//Used to set up 2D coordinates. Set a value for your top left and bottom right points, and you'll create a coordinate system for that.
	TheRenderer::instance->SetOrtho(BOTTOM_LEFT, TOP_RIGHT);
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
#if defined _DEBUG
    _CrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF | _CRTDBG_ALLOC_MEM_DF);
    _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE);
    _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
#endif

    MSG msg = {0};
    WNDCLASSEX wcl = {0};

    wcl.cbSize = sizeof(wcl);
    wcl.style = CS_OWNDC | CS_HREDRAW | CS_VREDRAW;
    wcl.lpfnWndProc = WindowProc;
    wcl.cbClsExtra = 0;
    wcl.cbWndExtra = 0;
    wcl.hInstance = g_hInstance = hInstance;
    wcl.hIcon = LoadIcon(0, IDI_APPLICATION);
    wcl.hCursor = LoadCursor(0, IDC_ARROW);
    wcl.hbrBackground = 0;
    wcl.lpszMenuName = 0;
    wcl.lpszClassName = "GLWindowClass";
    wcl.hIconSm = 0;

    if (!RegisterClassEx(&wcl))
        return 0;

    g_hWnd = CreateAppWindow(wcl, 0);

    if (g_hWnd)
    {

        InitGL();
        ToggleFullScreen();


        glDisable(GL_MULTISAMPLE_ARB);


        ShowWindow(g_hWnd, nShowCmd);
        UpdateWindow(g_hWnd);

        while (true)
        {
            while (PeekMessage(&msg, 0, 0, 0, PM_REMOVE))
            {
                if (msg.message == WM_QUIT)
                    break;

                TranslateMessage(&msg);
                DispatchMessage(&msg);
            }

            if (msg.message == WM_QUIT)
                break;


            if (keys[VK_ESCAPE])
            {
                msg.message = WM_QUIT ;
            }

            if (g_hasFocus)
            {
                RenderGL();
                SwapBuffers(g_hDC);
                ProcessKeyboard();
            }
            else
            {
                WaitMessage();
            }
        }


        Cleanup();
        UnregisterClass(wcl.lpszClassName, hInstance);
    }

    return static_cast<int>(msg.wParam);
}
Esempio n. 19
0
int WINAPI WinMain (HINSTANCE hThisInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR lpszArgument,
                     int nCmdShow)
{
    HWND hwnd;               /* This is the handle for our window */
    MSG messages;            /* Here messages to the application are saved */
    WNDCLASSEX wincl;        /* Data structure for the windowclass */

    /* The Window structure */
    wincl.hInstance = hThisInstance;
    wincl.lpszClassName = szClassName;
    wincl.lpfnWndProc = WindowProcedure;      /* This function is called by windows */
    wincl.style = CS_DBLCLKS;                 /* Catch double-clicks */
    wincl.cbSize = sizeof (WNDCLASSEX);

    /* Use default icon and mouse-pointer */
    wincl.hIcon = LoadIcon (NULL, IDI_APPLICATION);
    wincl.hIconSm = LoadIcon (NULL, IDI_APPLICATION);
    wincl.hCursor = LoadCursor (NULL, IDC_ARROW);
    wincl.lpszMenuName = NULL;                 /* No menu */
    wincl.cbClsExtra = 0;                      /* No extra bytes after the window class */
    wincl.cbWndExtra = 0;                      /* structure or the window instance */
    /* Use Windows's default colour as the background of the window */
    wincl.hbrBackground = (HBRUSH)CreateSolidBrush(RGB(255,255,255));

    /* Register the window class, and if it fails quit the program */
    if (!RegisterClassEx (&wincl))
        return 0;

    /* The class is registered, let's create the program*/
    hwnd = CreateWindowEx (
           0,                   /* Extended possibilites for variation */
           szClassName,         /* Classname */
           _T("Lab4 WP"),       /* Title Text */
           WS_OVERLAPPEDWINDOW, /* default window */
           CW_USEDEFAULT,       /* Windows decides the position */
           CW_USEDEFAULT,       /* where the window ends up on the screen */
           width,                 /* The programs width */
           height,                 /* and height in pixels */
           HWND_DESKTOP,        /* The window is a child-window to desktop */
           NULL,                /* No menu */
           hThisInstance,       /* Program Instance handler */
           NULL                 /* No Window Creation data */
           );

    if (!SetTimer(hwnd, ID_TIMER, speed, NULL)) {
        MessageBox(hwnd, "Too many clocks or timers!", szClassName, MB_ICONEXCLAMATION | MB_OK);
        return FALSE;
    }

    /* Make the window visible on the screen */
    ShowWindow (hwnd, nCmdShow);
    UpdateWindow(hwnd);

    /* Run the message loop. It will run until GetMessage() returns 0 */
    while (GetMessage (&messages, NULL, 0, 0))
    {
        /* Translate virtual-key messages into character messages */
        TranslateMessage(&messages);
        /* Send message to WindowProcedure */
        DispatchMessage(&messages);
    }

    /* The program return-value is 0 - The value that PostQuitMessage() gave */
    return messages.wParam;
}
int Win32Application::Run (
    D3D12DemoBase * demo,
    HINSTANCE hInstance,
    int nCmdShow
) {
    assert(demo);

	//-- Initialize the window class:
	WNDCLASSEX windowClass = { 0 };
	windowClass.cbSize = sizeof(WNDCLASSEX);
	windowClass.style = CS_HREDRAW | CS_VREDRAW;
	windowClass.lpfnWndProc = WindowProc;
	windowClass.hInstance = hInstance;
	windowClass.hCursor = LoadCursor(NULL, IDC_ARROW);
	windowClass.lpszClassName = "DXSampleClass";
	RegisterClassEx(&windowClass);

    //-- Center window:
    RECT windowRect;
	GetClientRect(GetDesktopWindow(), &windowRect);
	long width = static_cast<LONG>(demo->GetWindowWidth());
	long height = static_cast<LONG>(demo->GetWindowHeight());
	windowRect.left = (windowRect.right / 2) - (width / 2);
	windowRect.top = (windowRect.bottom / 2) - (height / 2);

	AdjustWindowRect(&windowRect, WS_OVERLAPPEDWINDOW, FALSE);

	// Create the window and store a handle to it.
	m_hwnd = CreateWindow (
		windowClass.lpszClassName,
		demo->GetWindowTitle(),
		WS_OVERLAPPEDWINDOW,
		windowRect.left,
		windowRect.top,
        width,
        height,
		nullptr,		// We have no parent window.
		nullptr,		// We aren't using menus.
		hInstance,
		demo            // Store pointer to the D3D12Demo in the user data slot.
                        // We'll retrieve this later within the WindowProc in order
                        // interact with the D3D12Demo instance.
    );

	// Run setup code common to all demos
	demo->Initialize();

	ShowWindow(m_hwnd, nCmdShow);

    //-- Timing information:
    static uint32 frameCount(0);
    static float fpsTimer(0.0f);

	// Main sample loop.
	MSG msg = {};
	while (msg.message != WM_QUIT)
	{
        // Start frame timer.
        auto timerStart = std::chrono::high_resolution_clock::now();
        // Process any messages in the queue.
        if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
        {
            // Translate virtual-key codes into character messages.
            TranslateMessage(&msg);

            // Dispatches a message to a the registered window procedure.
            DispatchMessage(&msg);
        }
        demo->BuildNextFrame();
		demo->PresentNextFrame();

        // End frame timer.
        auto timerEnd = std::chrono::high_resolution_clock::now();
        ++frameCount;

        auto timeDelta = 
            std::chrono::duration<double, std::milli>(timerEnd - timerStart).count();
        fpsTimer += (float)timeDelta;

        //-- Update window title only after so many milliseconds:
        if (fpsTimer > 400.0f) {
			float msPerFrame = fpsTimer / float (frameCount);
			float fps = float (frameCount) / fpsTimer * 1000.0f;
			char buffer[256];
			sprintf (buffer, "%s - %.1f fps (%.2f ms)",
				demo->GetWindowTitle (), fps, msPerFrame);
			::SetWindowText (m_hwnd, buffer);

			// Reset timing info.
			fpsTimer = 0.0f;
			frameCount = 0;
		}
	}

	// Flush command-queue before releasing resources.
	demo->PrepareCleanup();

	// Return this part of the WM_QUIT message to Windows.
	return static_cast<char>(msg.wParam);
}
Esempio n. 21
0
void openWindow()
{
	WNDCLASSEX wc;
	//DEVMODE dmScreenSettings;
	int posX, posY;


	// Get the instance of this application.
	g_hinstance = GetModuleHandle(NULL);

	// clear out the window class for use
	ZeroMemory(&wc, sizeof(WNDCLASSEX));

	// fill in the struct with the needed information
	//Step 1: Registering the Window Class
	wc.cbSize = sizeof(WNDCLASSEX);
	wc.style = 0;
	wc.lpfnWndProc = WndProc;
	wc.cbClsExtra = 0;
	wc.cbWndExtra = 0;
	wc.hInstance = g_hinstance;
	wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
	wc.hCursor = LoadCursor(NULL, IDC_ARROW);
	wc.hbrBackground = (HBRUSH) (COLOR_WINDOW + 1);
	wc.lpszMenuName = NULL;
	wc.lpszClassName = "Demo";
	wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION);

	// Register the window class.
	if (!RegisterClassEx(&wc))
	{
		MessageBox(NULL, "Window Registration Failed!", "Error!",
			MB_ICONEXCLAMATION | MB_OK);
		return;
	}

	// Determine the resolution of the clientss desktop screen.
	g_screenWidth = GetSystemMetrics(SM_CXSCREEN);
	g_screenHeight = GetSystemMetrics(SM_CYSCREEN);


	// If windowed then set it to 800x600 resolution.
	g_screenWidth = 1920;
	g_screenHeight = 1080;

	// Place the window in the middle of the screen.
	posX = 500;
	posY = 100;
	

	// Create the window with the screen settings and get the handle to it.
	g_hwnd = CreateWindowEx(	0,
								"Demo",    // name of the window class
								"Muret Demo",   // title of the window
								WS_POPUP,    // window style
								posX,    // x-position of the window
								posY,    // y-position of the window
								g_screenWidth,    // width of the window
								g_screenHeight,    // height of the window
								NULL,    // we have no parent window, NULL
								NULL,    // we aren't using menus, NULL
								g_hinstance,    // application handles
								NULL);    // used with multiple windows, NULL

	MoveWindow(g_hwnd, 0, 0, g_screenWidth, g_screenHeight, true);

	int TimmerID = SetTimer( g_hwnd , 0 , 1000 , NULL);

	int lastError = GetLastError();
	

	// Bring the window up on the screen and set it as main focus.
	ShowWindow(g_hwnd, g_nCmdShow);

	// Hide the mouse cursor.
	//ShowCursor(false);

	return;
}
Esempio n. 22
0
// main entry
int main(int argc,char **argv)
{
	WNDCLASSEX wcex;
	HWND hwnd;
	MSG msg;
	int ret;
/*
{
	HINSTANCE ret;
	HANDLE h;
	WIN32_FIND_DATA fd;
	
	//CreateProcess
	
	h = FindFirstFile("E:\\WINDOWS\\system32\\gpedit.msc",&fd);
	if (h != INVALID_HANDLE_VALUE)
	{
		printf("found\n");
		FindClose(h);
	}
	else
	{
		printf("not found\n");
	}
	
	ret = ShellExecute(0,0,L"E:\\WINDOWS\\system32\\gpedit.msc",0,L"E:\\WINDOWS\\system32",SW_SHOWNORMAL);
	printf("exec %d\n",ret);
	return 0;
}
*/
	printf("Everything IPC test\n");

	ZeroMemory(&wcex,sizeof(wcex));
	wcex.cbSize = sizeof(wcex);
	
	if (!GetClassInfoEx(GetModuleHandle(0),TEXT("IPCTEST"),&wcex))
	{
		ZeroMemory(&wcex,sizeof(wcex));
		wcex.cbSize = sizeof(wcex);
		wcex.hInstance = GetModuleHandle(0);
		wcex.lpfnWndProc = window_proc;
		wcex.lpszClassName = TEXT("IPCTEST");
		
		if (!RegisterClassEx(&wcex))
		{
			printf("failed to register IPCTEST window class\n");
			
			return 1;
		}
	}
	
	if (!(hwnd = CreateWindow(
		TEXT("IPCTEST"),
		TEXT(""),
		0,
		0,0,0,0,
		0,0,GetModuleHandle(0),0)))
	{
		printf("failed to create IPCTEST window\n");
		
		return 1;
	}
/*
	if (!sendquery(hwnd,TEXT("New Text Document.txt"))) 
	{
		return 1;
	}
*/
	if (!sendquery(hwnd,TEXT("Everything")))
	{
		return 1;
	}

	// message pump
loop:

	WaitMessage();
	
	// update windows
	while(PeekMessage(&msg,NULL,0,0,0)) 
	{
		ret = (int)GetMessage(&msg,0,0,0);
		if (ret == -1) goto exit;
		if (!ret) goto exit;
		
		// let windows handle it.
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}			
	
	goto loop;

exit:
	getchar();
		
	return 0;
}
void SystemClass::InitializeWindows(int& screenWidth, int& screenHeight)
{
	WNDCLASSEX wc;
	DEVMODE dmScreenSettings;
	int posX, posY;


	// Get an external pointer to this object.	
	ApplicationHandle = this;

	// Get the instance of this application.
	m_hinstance = GetModuleHandle(NULL);

	// Give the application a name.
	m_applicationName = L"Engine";

	// Setup the windows class with default settings.
	wc.style         = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
	wc.lpfnWndProc   = WndProc;
	wc.cbClsExtra    = 0;
	wc.cbWndExtra    = 0;
	wc.hInstance     = m_hinstance;
	wc.hIcon		 = LoadIcon(NULL, IDI_WINLOGO);
	wc.hIconSm       = wc.hIcon;
	wc.hCursor       = LoadCursor(NULL, IDC_ARROW);
	wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
	wc.lpszMenuName  = NULL;
	wc.lpszClassName = m_applicationName;
	wc.cbSize        = sizeof(WNDCLASSEX);
	
	// Register the window class.
	RegisterClassEx(&wc);

	// Determine the resolution of the clients desktop screen.
	screenWidth  = GetSystemMetrics(SM_CXSCREEN);
	screenHeight = GetSystemMetrics(SM_CYSCREEN);

	// Setup the screen settings depending on whether it is running in full screen or in windowed mode.
	if(FULL_SCREEN)
	{
		// If full screen set the screen to maximum size of the users desktop and 32bit.
		memset(&dmScreenSettings, 0, sizeof(dmScreenSettings));
		dmScreenSettings.dmSize       = sizeof(dmScreenSettings);
		dmScreenSettings.dmPelsWidth  = (unsigned long)screenWidth;
		dmScreenSettings.dmPelsHeight = (unsigned long)screenHeight;
		dmScreenSettings.dmBitsPerPel = 32;			
		dmScreenSettings.dmFields     = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;

		// Change the display settings to full screen.
		ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN);

		// Set the position of the window to the top left corner.
		posX = posY = 0;
	}
	else
	{
		// If windowed then set it to 800x600 resolution.
		screenWidth  = 800;
		screenHeight = 600;

		// Place the window in the middle of the screen.
		posX = (GetSystemMetrics(SM_CXSCREEN) - screenWidth)  / 2;
		posY = (GetSystemMetrics(SM_CYSCREEN) - screenHeight) / 2;
	}

	// Create the window with the screen settings and get the handle to it.
	m_hwnd = CreateWindowEx(WS_EX_APPWINDOW, m_applicationName, m_applicationName, 
						    WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_POPUP,
						    posX, posY, screenWidth, screenHeight, NULL, NULL, m_hinstance, NULL);

	// Bring the window up on the screen and set it as main focus.
	ShowWindow(m_hwnd, SW_SHOW);
	SetForegroundWindow(m_hwnd);
	SetFocus(m_hwnd);

	// Hide the mouse cursor.
	ShowCursor(false);

	return;
}
Esempio n. 24
0
//////////////////////////////////////////////////////////////////////////////
//WINMAIN
//////////////////////////////////////////////////////////////////////////////
int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nShowCmd)
{
	//assign instance to global variable
	hInstMain=hInstance;

	//create window class
	WNDCLASSEX wcx;

	//set the size of the structure
	wcx.cbSize=sizeof(WNDCLASSEX);

	//class style
	wcx.style=CS_OWNDC | CS_HREDRAW | CS_VREDRAW | CS_DBLCLKS;

	//window procedure
	wcx.lpfnWndProc=TheWindowProc;

	//class extra
	wcx.cbClsExtra=0;

	//window extra
	wcx.cbWndExtra=0;

	//application handle
	wcx.hInstance=hInstMain;

	//icon
	wcx.hIcon=LoadIcon(NULL,IDI_APPLICATION);

	//cursor
	wcx.hCursor=LoadCursor(NULL,IDC_ARROW);

	//background color
	wcx.hbrBackground=(HBRUSH)GetStockObject(BLACK_BRUSH);

	//menu
	wcx.lpszMenuName=NULL;

	//class name
	wcx.lpszClassName=WINDOWCLASS;

	//small icon
	wcx.hIconSm=NULL;

	//register the window class, return 0 if not successful
	if(!RegisterClassEx(&wcx)) return(0);

	//create main window
	hWndMain=CreateWindowEx(0,WINDOWCLASS,WINDOWTITLE, WS_POPUP | WS_VISIBLE,0,0,320,240,NULL,NULL,hInstMain,NULL);

	//error check
	if(!hWndMain) return(0);

	//if program initialization failed, then return with 0
	if(!Prog_Init()) return(0);

	//message structure
	MSG msg;

	//message pump
	for(;;)	
	{
		//look for a message
		if(PeekMessage(&msg,NULL,0,0,PM_REMOVE))
		{
			//there is a message

			//check that we arent quitting
			if(msg.message==WM_QUIT) break;
			
			//translate message
			TranslateMessage(&msg);

			//dispatch message
			DispatchMessage(&msg);
		}

		//run main game loop
		Prog_Loop();
	}
	
	//clean up program data
	Prog_Done();

	//return the wparam from the WM_QUIT message
	return(msg.wParam);
}
Esempio n. 25
0
WindowDetails* DefineWindow(HINSTANCE hInstance, int nShowCmd)
{
	WindowDetails* details = calloc(1, sizeof(WindowDetails));
	details->Height = gWindowHeight;
	details->Width = gWindowWidth;

	int bufferSize = details->Height*details->Width * sizeof(int);
	details->BackBuffer = calloc(1, bufferSize); //4 = bytes to display RGB

	details->BitMapInfo.bmiHeader.biSize = sizeof(details->BitMapInfo.bmiHeader);
	details->BitMapInfo.bmiHeader.biWidth = details->Width;
	details->BitMapInfo.bmiHeader.biHeight = -details->Height;
	details->BitMapInfo.bmiHeader.biPlanes = 1;
	details->BitMapInfo.bmiHeader.biBitCount = 32;
	details->BitMapInfo.bmiHeader.biCompression = BI_RGB;

	//define window
	WNDCLASSEX wc = { 0 };
	wc.cbSize = sizeof(wc);
#pragma warning(disable : 4028)
	wc.lpfnWndProc = WndProc;
	wc.hInstance = hInstance;
	wc.hCursor = LoadCursor(NULL, IDC_ARROW);

	wc.lpszClassName = L"Game of Life";

	if (!RegisterClassEx(&wc))
		return NULL;

	RECT adjustedRect = { 0 };
	adjustedRect.bottom = gWindowHeight;
	adjustedRect.right = gWindowWidth;
	AdjustWindowRect(&adjustedRect, WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_VISIBLE, FALSE);

	HWND hwndWindow = CreateWindowExW(
		0,
		L"Game of Life",
		&title,
		WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_VISIBLE,
		CW_USEDEFAULT,
		CW_USEDEFAULT,
		Difference(adjustedRect.left, adjustedRect.right),
		Difference(adjustedRect.bottom, adjustedRect.top),
		NULL,
		NULL,
		0,
		0);

	details->Window = hwndWindow;
	details->DC = GetDC(hwndWindow);
	ShowWindow(hwndWindow, nShowCmd);

	WNDCLASSEX childWC = { 0 };
	childWC.cbSize = sizeof(childWC);
#pragma warning(disable : 4028)
	childWC.lpfnWndProc = WndProc;
	childWC.hInstance = 0;
	childWC.hCursor = LoadCursor(NULL, IDC_ARROW);

	childWC.lpszClassName = L"Options";

	if (RegisterClassEx(&childWC))
	{
		RECT adjustedRect = { 0 };
		adjustedRect.bottom = 200;
		adjustedRect.right = 100;
		AdjustWindowRect(&adjustedRect, WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_VISIBLE, FALSE);

		HWND child = CreateWindowExW(
			0,
			L"Options",
			L"Options",
			WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_VISIBLE,
			CW_USEDEFAULT,
			CW_USEDEFAULT,
			Difference(adjustedRect.left, adjustedRect.right),
			Difference(adjustedRect.bottom, adjustedRect.top),
			NULL,
			NULL,
			0,
			0);

		CreateWindowExW(0, L"BUTTON", L"Restart", WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON, 0, 0, adjustedRect.right + 12, 20, child, (HMENU)RESTART_BTN, 0, NULL);
		CreateWindowExW(0, L"BUTTON", L"Cycle Mode", WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON, 0, 20, adjustedRect.right + 12, 20, child, (HMENU)CYCLE_BTN, 0, NULL);
		CreateWindowExW(0, L"BUTTON", L"Border Toggle", WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON, 0, 40, adjustedRect.right + 12, 20, child, (HMENU)BORDER_TOGGLE_BTN, 0, NULL);
		CreateWindowExW(0, L"BUTTON", L"Pause/Resume", WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON, 0, 60, adjustedRect.right + 12, 20, child, (HMENU)PAUSE_BTN, 0, NULL);

		CreateWindowExW(0, L"BUTTON", L"Faster", WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON, 0, 80, (adjustedRect.right + 12) / 2, 20, child, (HMENU)SPEED_INCREASE_BTN, 0, NULL);
		CreateWindowExW(0, L"BUTTON", L"Slower", WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON, (adjustedRect.right + 12) / 2, 80, (adjustedRect.right + 12) / 2, 20, child, (HMENU)SPEED_DECREASE_BTN, 0, NULL);

		CreateWindowExW(0, L"BUTTON", L"Size+", WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON, 0, 100, (adjustedRect.right + 12) / 2, 20, child, (HMENU)RESIZE_UP_BTN, 0, NULL);
		CreateWindowExW(0, L"BUTTON", L"Size-", WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON, (adjustedRect.right + 12) / 2, 100, (adjustedRect.right + 12) / 2, 20, child, (HMENU)RESIZE_DOWN_BTN, 0, NULL);

		ShowWindow(child, nShowCmd);
	}

	return details;
}
Esempio n. 26
0
// WINMAIN ////////////////////////////////////////////////
int WINAPI WinMain(	HINSTANCE hinstance,
					HINSTANCE hprevinstance,
					LPSTR lpcmdline,
					int ncmdshow)
{

WNDCLASSEX winclass; // this will hold the class we create
HWND	   hwnd;	 // generic window handle
MSG		   msg;		 // generic message
HDC        hdc;      // graphics device context

// first fill in the window class stucture
winclass.cbSize         = sizeof(WNDCLASSEX);
winclass.style			= CS_DBLCLKS | CS_OWNDC | 
                          CS_HREDRAW | CS_VREDRAW;
winclass.lpfnWndProc	= WindowProc;
winclass.cbClsExtra		= 0;
winclass.cbWndExtra		= 0;
winclass.hInstance		= hinstance;
winclass.hIcon			= LoadIcon(NULL, IDI_APPLICATION);
winclass.hCursor		= LoadCursor(NULL, IDC_ARROW); 
winclass.hbrBackground	= (HBRUSH)GetStockObject(BLACK_BRUSH);
winclass.lpszMenuName	= NULL;
winclass.lpszClassName	= WINDOW_CLASS_NAME;
winclass.hIconSm        = LoadIcon(NULL, IDI_APPLICATION);

// save hinstance in global
hinstance_app = hinstance;

// register the window class
if (!RegisterClassEx(&winclass))
	return(0);

// create the window
if (!(hwnd = CreateWindowEx(NULL,                  // extended style
                            WINDOW_CLASS_NAME,     // class
						    "DirectDraw Full-Screen Demo", // title
						    WS_POPUP | WS_VISIBLE,
					 	    0,0,	  // initial x,y
						    SCREEN_WIDTH,SCREEN_HEIGHT,  // initial width, height
						    NULL,	  // handle to parent 
						    NULL,	  // handle to menu
						    hinstance,// instance of this application
						    NULL)))	// extra creation parms
return(0);

// save main window handle
main_window_handle = hwnd;

// initialize game here
Game_Init();

// enter main event loop
while(TRUE)
	{
    // test if there is a message in queue, if so get it
	if (PeekMessage(&msg,NULL,0,0,PM_REMOVE))
	   { 
	   // test if this is a quit
       if (msg.message == WM_QUIT)
           break;
	
	   // translate any accelerator keys
	   TranslateMessage(&msg);

	   // send the message to the window proc
	   DispatchMessage(&msg);
	   } // end if
    
       // main game processing goes here
       Game_Main();
       
	} // end while

// closedown game here
Game_Shutdown();

// return to Windows like this
return(msg.wParam);

} // end WinMain
Esempio n. 27
0
//--------------------------------------------------------------------------
// WinMain() -> Função principal
//--------------------------------------------------------------------------
int WINAPI WinMain(HINSTANCE hInstance,
                   HINSTANCE hPrevInstance,
                   LPSTR lpCmdLine,
                   int nCmdShow)
{
  // Cria a classe da janela e especifica seus atributos
  WNDCLASSEX wcl;
  wcl.cbSize = sizeof(WNDCLASSEX);
  wcl.style = CS_HREDRAW | CS_VREDRAW;
  wcl.lpfnWndProc = (WNDPROC)WindowProc;
  wcl.cbClsExtra = 0;
  wcl.cbWndExtra = 0;
  wcl.hInstance = hInstance;
  wcl.hIcon = LoadIcon(NULL, IDI_APPLICATION);
  wcl.hCursor = LoadCursor(NULL, IDC_ARROW);
  wcl.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
  wcl.lpszMenuName = NULL;
  wcl.lpszClassName = WINDOW_CLASS;
  wcl.hIconSm = LoadIcon(NULL, IDI_APPLICATION);

  // Registra a classe da janela
  if(RegisterClassEx(&wcl))
  {
    // Cria a janela principal do programa
    HWND hWnd = NULL;
    hWnd = CreateWindowEx(
           NULL,
		   WINDOW_CLASS,
		   WINDOW_TITLE,
		   WS_OVERLAPPEDWINDOW | WS_VISIBLE,
		   (GetSystemMetrics(SM_CXSCREEN) - WINDOW_WIDTH) / 2,
		   (GetSystemMetrics(SM_CYSCREEN) - WINDOW_HEIGHT) / 2,
		   WINDOW_WIDTH,
		   WINDOW_HEIGHT,
		   HWND_DESKTOP,
		   NULL,
		   hInstance,
		   NULL);

    // Verifica se a janela foi criada
    if(hWnd)
    {
      // Mostra a janela
      ShowWindow(hWnd, nCmdShow);
      UpdateWindow(hWnd);

      // Armazena dados da mensagem que será obtida
      MSG msg;

      // Loop de mensagens, enquanto mensagem não for WM_QUIT,
      // obtém mensagem da fila de mensagens
      while(GetMessage(&msg, NULL, 0, 0) > 0)
      {
        // Traduz teclas virtuais ou aceleradoras (de atalho)
        TranslateMessage(&msg);

        // Envia mensagem para a função que processa mensagens (WindowProc)
        DispatchMessage(&msg);
      }

      // Retorna ao Windows com valor de msg.wParam
      return((int)msg.wParam);
     }
     // Se a janela não foi criada
     else
     {
       // Exibe mensagem de erro e sai do programa
       MessageBox(NULL, "Não foi possível criar janela.", "Erro!", MB_OK | MB_ICONERROR);

       return(0);
     }
  }
  // Se a classe da janela não foi registrada
  else
  {
    // Exibe mensagem de erro e sai do programa
    MessageBox(NULL, "Não foi possível registrar a classe da janela.", "Erro!", MB_OK | MB_ICONERROR);

    return(0);
  }
	
  // Retorna ao Windows sem passar pelo loop de mensagens
  return(0);
}
Esempio n. 28
0
int WINAPI WinMain (HINSTANCE hThisInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR lpszArgument,
                     int nCmdShow)
{
    MSG messages;            /* Here messages to the application are saved */
    WNDCLASSEX wincl;        /* Data structure for the windowclass */

    /* The Window structure */
    wincl.hInstance = hThisInstance;
    wincl.lpszClassName = szClassName;
    wincl.lpfnWndProc = WindowProcedure;      /* This function is called by windows */
    wincl.style = CS_DBLCLKS;                 /* Catch double-clicks */
    wincl.cbSize = sizeof (WNDCLASSEX);

    /* Use default icon and mouse-pointer */
    wincl.hIcon = LoadIcon (NULL, IDI_APPLICATION);
    wincl.hIconSm = LoadIcon (NULL, IDI_APPLICATION);
    wincl.hCursor = LoadCursor (NULL, IDC_ARROW);
    wincl.lpszMenuName = NULL;                 /* No menu */
    wincl.cbClsExtra = 0;                      /* No extra bytes after the window class */
    wincl.cbWndExtra = 0;                      /* structure or the window instance */
    /* Use Windows's default colour as the background of the window */
    wincl.hbrBackground = (HBRUSH) COLOR_BACKGROUND;

    /* Register the window class, and if it fails quit the program */
    if (!RegisterClassEx (&wincl))
        return 0;

    /* The class is registered, let's create the program*/
    mainHwnd = CreateWindowEx (
           0,                   /* Extended possibilites for variation */
           szClassName,         /* Classname */
           _T("Code::Blocks Template Windows App"),       /* Title Text */
           WS_OVERLAPPEDWINDOW, /* default window */
           CW_USEDEFAULT,       /* Windows decides the position */
           CW_USEDEFAULT,       /* where the window ends up on the screen */
           544,                 /* The programs width */
           375,                 /* and height in pixels */
           HWND_DESKTOP,        /* The window is a child-window to desktop */
           NULL,                /* No menu */
           hThisInstance,       /* Program Instance handler */
           NULL                 /* No Window Creation data */
           );

	TCHAR settingSzClassName[ ] = _T("Some_text_here");
	WinWindows wincSettingObject(settingSzClassName,hThisInstance,SW_SHOWDEFAULT);
	WNDCLASSEX wincSetting = wincSettingObject.getWinClass(EditableWindowProcedure);
	if( !wincSettingObject.getWinRegisterClass())
		return 0;
	settingHwnd = wincSettingObject.getWinHWND(250,100,_T("Setting"));

    /* Make the window visible on the screen */
    ShowWindow (mainHwnd, nCmdShow);

    /* Run the message loop. It will run until GetMessage() returns 0 */
    while (GetMessage (&messages, NULL, 0, 0))
    {
        /* Translate virtual-key messages into character messages */
        TranslateMessage(&messages);
        /* Send message to WindowProcedure */
        DispatchMessage(&messages);
    }

    /* The program return-value is 0 - The value that PostQuitMessage() gave */
    return messages.wParam;
}
Esempio n. 29
0
bool WinApp::Initialize(HINSTANCE hInst, const std::wstring& title, int w, int h)
{
    m_hInst = hInst;
    m_wndTitle = title;
    m_wndClass = title + L"_WndClass";


    m_clientWidth = w;
    m_clientHeight = h;

    m_width = w;
    m_height = h;

    WNDCLASSEX wcex;

    wcex.cbSize = sizeof(WNDCLASSEX);

    wcex.style			= CS_HREDRAW | CS_VREDRAW;
    wcex.lpfnWndProc	= WndProc;
    wcex.cbClsExtra		= 0;
    wcex.cbWndExtra		= 0;
    wcex.hInstance		= m_hInst;
    wcex.hIcon			= NULL;
    wcex.hCursor		= LoadCursor(NULL, IDC_ARROW);
    wcex.hbrBackground	= (HBRUSH)GetStockObject(BLACK_BRUSH);
    wcex.lpszMenuName	= NULL;
    wcex.lpszClassName	= m_wndClass.c_str();
    wcex.hIconSm		= NULL;


    if(FALSE == RegisterClassEx(&wcex))
    {
        return false;
    }


    m_hWnd = CreateWindow(m_wndClass.c_str(),
                          m_wndTitle.c_str(),
                          (WS_OVERLAPPED | WS_CAPTION | WS_MINIMIZEBOX | WS_SYSMENU),
                          CW_USEDEFAULT,
                          0,
                          m_width,
                          m_height,
                          NULL,
                          NULL,
                          m_hInst,
                          NULL);

    if (!m_hWnd)
    {
        return false;
    }

    AdjustWindow(w, h);

    ShowWindow(m_hWnd, SW_SHOW);
    UpdateWindow(m_hWnd);

    if(OnInit() == false)
    {
        return false;
    }

    return true;
}
Esempio n. 30
0
int WINAPI WinMain(HINSTANCE hInstance,
                   HINSTANCE hPrevInstance,
                   LPSTR lpCmdLine,
                   int nCmdShow)
{
    WNDCLASSEX wcex;

    wcex.cbSize = sizeof(WNDCLASSEX);
    wcex.style          = CS_HREDRAW | CS_VREDRAW;
    wcex.lpfnWndProc    = WndProc;
    wcex.cbClsExtra     = 0;
    wcex.cbWndExtra     = 0;
    wcex.hInstance      = hInstance;
    wcex.hIcon          = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_APPLICATION));
    wcex.hCursor        = LoadCursor(NULL, IDC_ARROW);
    wcex.hbrBackground  = (HBRUSH)(COLOR_WINDOW+1);
    wcex.lpszMenuName   = NULL;
    wcex.lpszClassName  = szWindowClass;
    wcex.hIconSm        = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_APPLICATION));

    if (!RegisterClassEx(&wcex))
    {
        MessageBox(NULL,
            _T("Call to RegisterClassEx failed!"),
            _T("Win32 Guided Tour"),
            NULL);

        return 1;
    }

    hInst = hInstance; // Store instance handle in our global variable
	/**
    @function CreateWindow
	@brief The function that creates the window.
	@param szWindowClass The class name
	@param szTitle Window Name
    @param WS_OVERLAPPEDWINDOW: the type of window to create
    @param CW_USEDEFAULT, CW_USEDEFAULT: initial position (x, y)
    @param 800/700 The width and height of the window
	@param NULL Handle to the parent window and menu handle
	@param hInstance Handle to application instance
	@param NULL Parameters transmitted from the WndProc
	*/
    HWND hWnd = CreateWindow(
        szWindowClass,
        szTitle,
        WS_OVERLAPPEDWINDOW,
        CW_USEDEFAULT, CW_USEDEFAULT,
        800, 700,
        NULL,
        NULL,
        hInstance,
        NULL
    );

    if (!hWnd)
    {
        MessageBox(NULL,
            _T("Call to CreateWindow failed!"),
            _T("Win32 Guided Tour"),
            NULL);

        return 1;
    }

    	/**
	@function ShowWindow
	@brief Function to display the window.
	@param hWnd Window Handle
	@param nCmdShow Window Display Mode
	*/
    ShowWindow(hWnd,
        nCmdShow);
	/**
	@function UpdateWindow
	@brief Function to update the window.
	@param hWnd Window Handle
	*/
    UpdateWindow(hWnd);

	/// The main message loop
    MSG msg;

	ULONGLONG prevTime = -1, curTime, deltaT;

	/// Call Start function
	StartGame();
/// Enter the infinite message loop
while(TRUE)
{
    /// Check to see if any messages are waiting in the queue
    while(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
    {
        /// Translate the message and dispatch it to WindowProc()
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    /// If the message is WM_QUIT, exit the while loop
    if(msg.message == WM_QUIT)
        break;

	/// Removing the number of milliseconds that have elapsed since the system was launched
	curTime = GetTickCount64();
	/// Determination of the time change
	if (prevTime == -1)
		deltaT = 0;
	else deltaT = curTime - prevTime;
	prevTime = curTime;

	/// Calling a function is responsible for the application physics
	if(!pause){
    DoPhysics(deltaT);
	}

	/// Calling a function that initiates a redraw window
	InvalidateRect(hWnd,NULL,1);
}

    return (int) msg.wParam;
}