コード例 #1
0
ファイル: acquiregraphics.cpp プロジェクト: karlgluck/Evidyon
//------------------------------------------------------------------------------------------------
// Name: acquireGraphics
// Desc: Implements a robust algorithm to create the Direct3D device
//------------------------------------------------------------------------------------------------
bool EvidyonClient::createD3DDevice(bool windowed, unsigned int requiredNumberOfBlendMatrices)
{
  // Get the main Direct3D object from the display structure
  IDirect3D9* d3d = d3d_;

  { // Display the adapter that we are using
    D3DADAPTER_IDENTIFIER9 identifier;
    if (!APP_WARNING(FAILED(d3d->GetAdapterIdentifier(D3DADAPTER_DEFAULT, 0, &identifier)))("Failed to get adapter information"))
      DEBUG_INFO("Using \"%s\"", identifier.Description);
  }

  // Set up the structure used to create the Direct3D device.
  D3DPRESENT_PARAMETERS d3dpp;
  ZeroMemory(&d3dpp, sizeof(d3dpp));

  // Initialize some parts of the parameters
  d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
  d3dpp.EnableAutoDepthStencil = TRUE;
  d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
  //d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_DEFAULT;
  d3dpp.BackBufferCount = 1;
  //d3dpp.Flags = D3DPRESENTFLAG_DISCARD_DEPTHSTENCIL;

  // Set up the rest of the parameters based on the windowed mode
  if (windowed)
  {
    d3dpp.Windowed = TRUE;
		d3dpp.BackBufferWidth  = config_.getSetting("Graphics", "ResolutionX", 800);
    d3dpp.BackBufferHeight = config_.getSetting("Graphics", "ResolutionY", 600);
    d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;

    // Create the application's window
    RECT rc = { 0, 0, d3dpp.BackBufferWidth, d3dpp.BackBufferHeight };
    AdjustWindowRect(&rc, WS_POPUPWINDOW|WS_CAPTION, FALSE);
    d3dpp.hDeviceWindow = CreateWindow(STRING_WINDOWCLASS,
                                       STRING_WINDOWTITLE, 
                                       WS_POPUPWINDOW|WS_CAPTION|WS_MINIMIZEBOX,
                                       50,
                                       50,
                                       rc.right-rc.left,
                                       rc.bottom-rc.top,
                                       NULL,
                                       NULL,
                                       GetModuleHandle(NULL),
                                       NULL);
  }
  else
  {
    // Get the current display mode (this should always succeed)
    D3DDISPLAYMODE displayMode;
    if (APP_ERROR(FAILED(d3d->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &displayMode)))("Couldn't get current display mode"))
      return false;

    // Use the current display mode
    d3dpp.Windowed = FALSE;
		d3dpp.BackBufferWidth  = config_.getSetting("Graphics", "ResolutionX", (int)displayMode.Width);
    d3dpp.BackBufferHeight = config_.getSetting("Graphics", "ResolutionY", (int)displayMode.Height);

    switch (config_.getSetting("Graphics", "ColorDepth", 16)) {
      default:
      case 16: d3dpp.BackBufferFormat = D3DFMT_R5G6B5; break;
      case 15: d3dpp.BackBufferFormat = D3DFMT_X1R5G5B5; break;
      case 24: d3dpp.BackBufferFormat = D3DFMT_R8G8B8; break;
      case 32: d3dpp.BackBufferFormat = D3DFMT_X8R8G8B8; break;
    }

    // Create the application's window
    d3dpp.hDeviceWindow = CreateWindow(STRING_WINDOWCLASS, STRING_WINDOWTITLE, 
                      WS_POPUP, 0, 0, d3dpp.BackBufferWidth, d3dpp.BackBufferHeight,
                      NULL, NULL, GetModuleHandle(NULL), NULL);
  }

  // Make sure a window was created
  if (APP_ERROR(d3dpp.hDeviceWindow == NULL)("Unable to create application window"))
  {
    // Try again in windowed mode if this was fullscreen; otherwise, fail
    if (!windowed)
      return createD3DDevice(true, requiredNumberOfBlendMatrices);
    else
      return false;
  }

  // Should we force the rendering into software mode?
  bool forceSoftwareMode = config_.getSetting("Graphics", "ForceSoftwareRendering", 0) == 1;

  // Parameters that will be used to create the device
  bool createHardwareDevice = !forceSoftwareMode;  // Use D3DCREATE_HARDWARE_VERTEXPROCESSING; otherwise, D3DCREATE_SOFTWARE_VERTEXPROCESSING
  bool createPureDevice = false;    // Set the D3DCREATE_PUREDEVICE flag.  Only valid if createHardwareDevice is true.
  bool createMixedDevice = false;   // Set the D3DCREATE_MIXED_VERTEXPROCESSING flag.  Only valid if createHardwareDevice is false.

  // Get device capabilities so we can determine what kind of device to make
  D3DCAPS9 devCaps;
  if (!APP_ERROR(FAILED(d3d->GetDeviceCaps(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, &devCaps)))("Couldn't get device capibilities"))
  {
    // Determine whether or not we can use a pure hardware device
    createPureDevice = createHardwareDevice && ((devCaps.DevCaps & D3DDEVCAPS_PUREDEVICE) != 0);


    if (APP_WARNING(devCaps.MaxVertexBlendMatrices < 4 || devCaps.MaxVertexBlendMatrixIndex + 1 < requiredNumberOfBlendMatrices)
        ("This computer's hardware doesn't support indexed blended animation; using software device to compensate"))
    {
      createHardwareDevice = false;
      createMixedDevice = false;    //createMixedDevice = true;
    }
  }

  createPureDevice = false;


  // Build the flags for the device creation procedure
  DWORD createFlags = createHardwareDevice ? (D3DCREATE_HARDWARE_VERTEXPROCESSING | (createPureDevice ? D3DCREATE_PUREDEVICE : 0)) :
               (createMixedDevice ? D3DCREATE_MIXED_VERTEXPROCESSING : D3DCREATE_SOFTWARE_VERTEXPROCESSING);

  // Create the Direct3D device here
  IDirect3DDevice9* d3dDevice;
  if (APP_ERROR(FAILED(d3d->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, d3dpp.hDeviceWindow, createFlags, &d3dpp, &d3dDevice)))("Failed to create optimal Direct3D device"))
  {
    // Set up the most generic-possible flags and attempt to create again
    d3dpp.PresentationInterval = 0;
    createFlags = D3DCREATE_SOFTWARE_VERTEXPROCESSING;
    createMixedDevice = false;

    // Try to create again
    if (APP_FATAL(FAILED(d3d->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, d3dpp.hDeviceWindow, createFlags, &d3dpp, &d3dDevice)))("Failed to create fallback Direct3D device"))
    {
      // If we were creating in fullscreen mode, try again in windowed mode
      if (!windowed)
      {
        // Kill the window we made
        DestroyWindow(d3dpp.hDeviceWindow);

        // Inidicate what's going to happen
        DEBUG_INFO("Failed to create a fullscreen device; trying windowed mode");

        // Try again in windowed mode
        return createD3DDevice(true, requiredNumberOfBlendMatrices);
      }
    }
    else
    {
      // Let the user know that we recovered
      DEBUG_INFO("Recovered from failure to create optimal D3D device by resorting to fallback settings");
    }
  }

  // Save the device and parameters as output
  d3d_device_ = d3dDevice;
  myMainWindow = d3dpp.hDeviceWindow;
  myUsingMixedDeviceFlag = createMixedDevice;
  myUsingSoftwareDeviceFlag = (createFlags & D3DCREATE_SOFTWARE_VERTEXPROCESSING) == D3DCREATE_SOFTWARE_VERTEXPROCESSING;
  memcpy_s(&d3d_params_, sizeof(d3d_params_), &d3dpp, sizeof(d3dpp));

  // Success
  return true;
}
コード例 #2
0
//-----------------------------------------------------------------------
// WinMain
//-----------------------------------------------------------------------
int APIENTRY WinMain(HINSTANCE _hInstance, HINSTANCE _hPrevInstance, LPSTR _lpCmdLine, int _nCmdShow)
{
	_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
	//_CrtSetBreakAlloc(143430);

	new CEngine();
	CEngine& engine = CEngine::GetSingleton();
	//*/
	// Register the window class
	WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, MsgProc, 0L, 0L, GetModuleHandle(NULL), NULL, NULL, NULL, NULL, APPLICATION_NAME, NULL };

	RegisterClassEx(&wc);


	// Calcular el tamano de nuestra ventana
	RECT rc = {
		0, 0, WIDTH, HEIGHT
	};
	AdjustWindowRect(&rc, WS_OVERLAPPEDWINDOW, FALSE);

	// Create the application's window
	HWND hWnd = CreateWindow(APPLICATION_NAME, APPLICATION_NAME, WS_OVERLAPPEDWINDOW, 100, 100, rc.right - rc.left, rc.bottom - rc.top, NULL, NULL, wc.hInstance, NULL);



	// Añadir aquí el Init de la applicacioón

	engine.Init();
	engine.getPhysXManager()->InitPhysx();

	CContextManager& context = *(CEngine::GetSingleton().getContextManager());
	context.CreateContext(hWnd, WIDTH, HEIGHT);

	ShowWindow(hWnd, SW_SHOWDEFAULT);

	context.CreateBackBuffer(hWnd, WIDTH, HEIGHT);

#ifndef _DEBUG
	ToggleFullscreen( hWnd );
#endif


	CPlayer *videoPlayer = NULL;

	// Initialize the player object.
	HRESULT hr = CPlayer::CreateInstance(hWnd, hWnd, &videoPlayer);

	CEngine::GetSingleton().setPlayerManager(videoPlayer);

	engine.getTextureManager()->Init();
	engine.getDebugRender()->Init();
	engine.getEffectsManager()->load("Data\\effects.xml");
	engine.getRenderableObjectTechniqueManager()->Load("Data\\pool_renderable_objects.xml");
	engine.getMaterialManager()->load("Data\\materials.xml");
	engine.getCookedMeshManager()->SetCookedMeshPath("Cache\\Cooked\\");
	engine.getStaticMeshManager()->Load("Data\\static_meshes.xml");
	engine.getAnimatedMeshManager()->Load("Data\\animated_models.xml");
	engine.getParticleManager()->Load("Data\\particle_classes.xml");
	engine.getLightManager()->Load("Data\\lights.xml");
	engine.getSceneRendererCommandManager()->Load("Data\\scene_renderer_commands.xml");
	engine.getSceneManager()->Initialize("Data\\Scenes\\");
	engine.getSoundManager()->InitAll("Data\\Sound\\Soundbanks\\SoundbanksInfo.xml", "Data\\Sound\\speakers.xml");

	{
		CInputManagerImplementation inputManager(hWnd);
		CInputManager::SetCurrentInputManager(&inputManager);
		inputManager.LoadCommandsFromFile("Data\\input.xml");

		engine.getCinematicManager()->LoadFilesInDir("Data\\Animations\\");



//#ifdef _DEBUG
		CDebugHelperImplementation debugHelper(context.GetDevice());
		CDebugHelper::SetCurrentDebugHelper(&debugHelper);
//#endif

		CApplication application(&context);
		engine.setApplication( &application );


		engine.getScriptManager()->Initialize("Data\\scripting.xml");

		engine.getComponentManager()->FirstInitialization();


		UpdateWindow(hWnd);
		MSG msg;
		ZeroMemory(&msg, sizeof(msg));

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

		// Añadir en el while la condición de salida del programa de la aplicación
		auto previousTime = std::chrono::high_resolution_clock::now();

		bool hasFocus = true;

		bool first = true;

		while (msg.message != WM_QUIT && !application.ShouldQuit())
		{
			if (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE))
			{
				if (!debugHelper.Update(msg.hwnd, msg.message, msg.wParam, msg.lParam))
				{
					TranslateMessage(&msg);
					DispatchMessage(&msg);
				}
			}
			else
			{
				if (! CEngine::GetSingleton().getPlayerManager()->IsVideoPlaying())
				{
					inputManager.BeginFrame();

					auto now = std::chrono::high_resolution_clock::now();
					double l_ElapsedTime = std::chrono::duration_cast<std::chrono::microseconds>( ( now - previousTime ) ).count() * 0.000001;
					CEngine::GetSingleton().getTimerManager()->m_elapsedTime = l_ElapsedTime;
					previousTime = now;

					application.Update(l_ElapsedTime);
					application.Render();
					application.PostRender( l_ElapsedTime );
					inputManager.EndFrame();
				}
				else
				{
					inputManager.BeginFrame();

					if (inputManager.IsActionActive("MOUSE_RELEASED"))
					{
						CEngine::GetSingleton().getPlayerManager()->Stop();
					}

					inputManager.EndFrame();
				}
			}
		}
	}

	CEngine::ReleaseSingleton();
	UnregisterClass(APPLICATION_NAME, wc.hInstance);
	return 0;
}
コード例 #3
0
VOID CGameProcedure::CreateMainWnd(VOID)
{
	//------------------------------------------------------
	//计算窗口大小
	m_bMinimized		= FALSE;
	m_bFullScreen		= TRUE;
	fVector2 fResoution;
	if (CGameProcedure::s_pVariableSystem->GetAs_Int("View_FullScreen"))
	{
		fResoution.x  = (float)::GetSystemMetrics(SM_CXSCREEN);
		fResoution.y  = (float)::GetSystemMetrics(SM_CYSCREEN);	
	}
	else
	{
		fResoution = s_pVariableSystem->GetAs_Vector2("View_Resoution");
	}
	CGameProcedure::m_fWindowFOV = fResoution.x / fResoution.y;
	SetRect(&m_rectWindow, 0, 0, (int)fResoution.x, (int)fResoution.y);
	AdjustWindowRect(&m_rectWindow, DEFWINDOW_STYLE, FALSE);

	SetRect(&m_rectFCOffset, m_rectWindow.left, m_rectWindow.top, 
		m_rectWindow.right-(int)fResoution.x, m_rectWindow.bottom-(int)fResoution.y);

	UINT dwX = (::GetSystemMetrics(SM_CXFULLSCREEN)-(m_rectWindow.right-m_rectWindow.left))/2;
	UINT dwY = (::GetSystemMetrics(SM_CYFULLSCREEN)-(m_rectWindow.bottom-m_rectWindow.top))/2;
	OffsetRect(&m_rectWindow, -m_rectFCOffset.left, -m_rectFCOffset.top);
	OffsetRect(&m_rectWindow, dwX, dwY);

	m_bActive			= true;
	m_bRenderingPaused	= FALSE;

	//------------------------------------------------------
	//注册窗口类
	WNDCLASSEX wcex;

	wcex.cbSize = sizeof(WNDCLASSEX); 
	wcex.style			= CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
	wcex.lpfnWndProc	= (WNDPROC)_MainWndProc;
	wcex.cbClsExtra		= 0;
	wcex.cbWndExtra		= 0;
	wcex.hInstance		= g_hInstance;
	wcex.hIcon			= LoadIcon(g_hInstance, (LPCTSTR)IDD_GAME_DIALOG);
	wcex.hCursor		= LoadCursor( NULL, IDC_ARROW );
	wcex.hbrBackground	= (HBRUSH)NULL; //GetStockObject(WHITE_BRUSH);
	wcex.lpszMenuName	= (LPCTSTR)NULL;
	wcex.lpszClassName	= MAINWINDOW_CLASS;
	wcex.hIconSm		= LoadIcon(wcex.hInstance, (LPCTSTR)IDI_SMALL);

	RegisterClassEx(&wcex);

	//------------------------------------------------------
	//创建窗口
	CHAR szTitle[MAX_PATH];
	_snprintf(szTitle, MAX_PATH, "%s %s (%s %s)", GAME_TITLE, VERSION_INFO, __DATE__, __TIME__);

	HWND hWnd = CreateWindowEx(NULL, MAINWINDOW_CLASS, szTitle, 
		DEFWINDOW_STYLE,
		m_rectWindow.left, m_rectWindow.top, 
		m_rectWindow.right-m_rectWindow.left, 
		m_rectWindow.bottom-m_rectWindow.top,
		NULL, NULL, g_hInstance, NULL);

	if (!hWnd)
	{
		TDThrow(_T("Can't create main window!"));
	}

	if (CGameProcedure::s_pVariableSystem->GetAs_Int("View_FullScreen"))
	{
		s_pEventSystem->PushEvent(GE_VARIABLE_CHANGED, "View_FullScreen", "1");
		s_pEventSystem->PushEvent(GE_CHAT_ADJUST_MOVE_CTL, (INT)fResoution.x, (INT)fResoution.y);
	}else
	{
		const STRING& strVariable = CGameProcedure::s_pVariableSystem->GetAs_String("View_Resoution");
		s_pEventSystem->PushEvent(GE_VARIABLE_CHANGED,"View_Resoution", strVariable.c_str());
		s_pEventSystem->PushEvent(GE_CHAT_ADJUST_MOVE_CTL, (INT)fResoution.x, (INT)fResoution.y);
	}

	ShowWindow(hWnd, SW_SHOW);
	UpdateWindow(hWnd);

	g_hMainWnd = hWnd;
}
コード例 #4
0
ファイル: DEMO.cpp プロジェクト: locpk/Mockingbird
DEMO::DEMO(HINSTANCE hinst, WNDPROC proc)
{
	// ****************** BEGIN WARNING ***********************// 
	application = hinst;
	appWndProc = proc;

	WNDCLASSEX  wndClass;
	ZeroMemory(&wndClass, sizeof(wndClass));
	wndClass.cbSize = sizeof(WNDCLASSEX);
	wndClass.lpfnWndProc = appWndProc;
	wndClass.lpszClassName = L"DirectXApplication";
	wndClass.hInstance = application;
	wndClass.hCursor = LoadCursor(NULL, IDC_ARROW);
	wndClass.hbrBackground = (HBRUSH)(COLOR_WINDOWFRAME);
	//wndClass.hIcon			= LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_FSICON));
	RegisterClassEx(&wndClass);

	RECT window_size = { 0, 0, (long)BACKBUFFER_WIDTH, (long)BACKBUFFER_HEIGHT };
	AdjustWindowRect(&window_size, WS_OVERLAPPEDWINDOW, false);

	window = CreateWindow(L"DirectXApplication", L"Mockingbird", WS_OVERLAPPEDWINDOW /*& ~(WS_THICKFRAME | WS_MAXIMIZEBOX)*/,
		CW_USEDEFAULT, CW_USEDEFAULT, window_size.right - window_size.left, window_size.bottom - window_size.top,
		NULL, NULL, application, this);

	ShowWindow(window, SW_SHOW);
	//********************* END WARNING ************************//



	//D3D Init
	DXGI_SWAP_CHAIN_DESC swapchain_DESC;
	ZeroMemory(&swapchain_DESC, sizeof(swapchain_DESC));
	swapchain_DESC.BufferCount = 1;
	swapchain_DESC.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
	swapchain_DESC.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT | DXGI_USAGE_SHADER_INPUT;
	swapchain_DESC.BufferDesc.Width = (UINT)BACKBUFFER_WIDTH;
	swapchain_DESC.BufferDesc.Height = (UINT)BACKBUFFER_HEIGHT;
	swapchain_DESC.BufferDesc.RefreshRate.Numerator = 60;
	swapchain_DESC.BufferDesc.RefreshRate.Denominator = 1;
	swapchain_DESC.OutputWindow = window;
#if MSAA
	swapchain_DESC.SampleDesc.Count = MSAA_COUNT;
#else
	swapchain_DESC.SampleDesc.Count = 1;
#endif
	swapchain_DESC.SampleDesc.Quality = D3D11_STANDARD_MULTISAMPLE_PATTERN;
	swapchain_DESC.Windowed = TRUE;

	//Create Device and Swapchain DEBUG
	D3D_FEATURE_LEVEL FeatureLevel = D3D_FEATURE_LEVEL_11_0;
	HRESULT hr = D3D11CreateDeviceAndSwapChain(
		NULL,
		D3D_DRIVER_TYPE_HARDWARE,
		NULL,
		D3D11_CREATE_DEVICE_DEBUG,
		&FeatureLevel,
		1,
		D3D11_SDK_VERSION,
		&swapchain_DESC,
		&pSwapchain,
		&pDevice,
		&featureLevel,
		&pDeviceContext);



	pDevice->CreateDeferredContext(0, &pDeferredDeviceContext);
	//Create Render Target View from back buffer
	ID3D11Texture2D* pBackBuffer = nullptr;
	pSwapchain->GetBuffer(0, __uuidof(ID3D11Texture2D), reinterpret_cast<void**>(&pBackBuffer));
	pDevice->CreateRenderTargetView(pBackBuffer, 0, &pRenderTargetView);
	SecureRelease(pBackBuffer);



	D3D11_TEXTURE2D_DESC renderToTextureDesc;
	ZeroMemory(&renderToTextureDesc, sizeof(renderToTextureDesc));
	renderToTextureDesc.Usage = D3D11_USAGE_DEFAULT;
	renderToTextureDesc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE;
	renderToTextureDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
	renderToTextureDesc.Height = swapchain_DESC.BufferDesc.Height;
	renderToTextureDesc.Width = swapchain_DESC.BufferDesc.Width;
	renderToTextureDesc.SampleDesc.Count = 1;
	renderToTextureDesc.ArraySize = 1;
	renderToTextureDesc.MipLevels = 1;
	pDevice->CreateTexture2D(&renderToTextureDesc, NULL, &pQuad_texture);
	pDevice->CreateRenderTargetView(pQuad_texture, 0, &pQuadRTV);
	quadDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
	quadDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
	quadDesc.Texture2D.MipLevels = 1;
	quadDesc.Texture2D.MostDetailedMip = 0;
	pDevice->CreateShaderResourceView(pQuad_texture, &quadDesc, &pQuadSRV);





	//Set up view port
	ZeroMemory(&viewport, sizeof(viewport));
	viewport.MaxDepth = 1;
	viewport.MinDepth = 0;
	viewport.TopLeftX = 0;
	viewport.TopLeftY = 0;
	viewport.Width = (float)swapchain_DESC.BufferDesc.Width / 2.0f;
	viewport.Height = (float)swapchain_DESC.BufferDesc.Height;

	ZeroMemory(&another_viewport, sizeof(another_viewport));
	another_viewport.MaxDepth = 1;
	another_viewport.MinDepth = 0;
	another_viewport.TopLeftX = (float)swapchain_DESC.BufferDesc.Width / 2.0f;
	another_viewport.TopLeftY = 0;
	another_viewport.Width = (float)swapchain_DESC.BufferDesc.Width / 2.0f;
	another_viewport.Height = (float)swapchain_DESC.BufferDesc.Height;




	//Set up Depth Buffer
	D3D11_TEXTURE2D_DESC ZBufferdesc;
	ZBufferdesc.Width = swapchain_DESC.BufferDesc.Width;
	ZBufferdesc.Height = swapchain_DESC.BufferDesc.Height;
	ZBufferdesc.MipLevels = 1;
	ZBufferdesc.ArraySize = 1;
	ZBufferdesc.Format = DXGI_FORMAT_D32_FLOAT;
	ZBufferdesc.SampleDesc.Count = swapchain_DESC.SampleDesc.Count;
	ZBufferdesc.SampleDesc.Quality = swapchain_DESC.SampleDesc.Quality;
	ZBufferdesc.Usage = D3D11_USAGE_DEFAULT;
	ZBufferdesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
	ZBufferdesc.CPUAccessFlags = 0;
	ZBufferdesc.MiscFlags = 0;
	pDevice->CreateTexture2D(&ZBufferdesc, 0, &pZBuffer);
	pDevice->CreateDepthStencilView(pZBuffer, NULL, &pDepthStencilView);
	pDeviceContext->OMSetRenderTargets(1, &pRenderTargetView, pDepthStencilView);




	//Load Star
	MyVertex* star = CreateStar();
	D3D11_BUFFER_DESC starBufferDesc;
	ZeroMemory(&starBufferDesc, sizeof(starBufferDesc));
	starBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
	starBufferDesc.ByteWidth = sizeof(MyVertex) * 12;
	starBufferDesc.CPUAccessFlags = NULL;
	starBufferDesc.Usage = D3D11_USAGE_IMMUTABLE;
	starBufferDesc.MiscFlags = 0;
	starBufferDesc.StructureByteStride = 0;
	D3D11_SUBRESOURCE_DATA starVerticesData;
	ZeroMemory(&starVerticesData, sizeof(starVerticesData));
	starVerticesData.pSysMem = star;
	pDevice->CreateBuffer(&starBufferDesc, &starVerticesData, &pStar);

	delete star;
	//Create Star Shaders
	pDevice->CreateVertexShader(Star_VS, sizeof(Star_VS), NULL, &pStar_VSShader);
	pDevice->CreatePixelShader(Star_PS, sizeof(Star_PS), NULL, &pStar_PSShader);


	//Create Star InputLayout
	D3D11_INPUT_ELEMENT_DESC starInputLayout[] =
	{
		{ "POSITION", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },
		{ "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },
	};
	pDevice->CreateInputLayout(starInputLayout, 2, Star_VS, sizeof(Star_VS), &pStar_inputLayout);

#pragma region starIndex 
	unsigned int starIndex[60];
	for (size_t i = 0; i < 30; i++)
	{
		if (i % 3 == 0)
		{
			starIndex[i] = 0;
		}
	}
	for (size_t i = 29; i < 60; i++)
	{
		if (i % 3 == 0)
		{
			starIndex[i] = 11;
		}
	}
	starIndex[1] = 1;
	starIndex[2] = 2;
	starIndex[4] = 2;
	starIndex[5] = 3;
	starIndex[7] = 3;
	starIndex[8] = 4;
	starIndex[10] = 4;
	starIndex[11] = 5;
	starIndex[13] = 5;
	starIndex[14] = 6;
	starIndex[16] = 6;
	starIndex[17] = 7;
	starIndex[19] = 7;
	starIndex[20] = 8;
	starIndex[22] = 8;
	starIndex[23] = 9;
	starIndex[25] = 9;
	starIndex[26] = 10;
	starIndex[28] = 10;
	starIndex[29] = 1;

	starIndex[31] = 1;
	starIndex[32] = 10;
	starIndex[34] = 10;
	starIndex[35] = 9;
	starIndex[37] = 9;
	starIndex[38] = 8;
	starIndex[40] = 8;
	starIndex[41] = 7;
	starIndex[43] = 7;
	starIndex[44] = 6;
	starIndex[46] = 6;
	starIndex[47] = 5;
	starIndex[49] = 5;
	starIndex[50] = 4;
	starIndex[52] = 4;
	starIndex[53] = 3;
	starIndex[55] = 3;
	starIndex[56] = 2;
	starIndex[58] = 2;
	starIndex[59] = 1;

#pragma endregion
	//Create Star Index Buffer
	D3D11_BUFFER_DESC starIndexBufferDesc;
	ZeroMemory(&starIndexBufferDesc, sizeof(starIndexBufferDesc));
	starIndexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
	starIndexBufferDesc.ByteWidth = sizeof(unsigned int) * 60;
	starIndexBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
	starIndexBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
	starIndexBufferDesc.MiscFlags = 0;
	starIndexBufferDesc.StructureByteStride = 0;
	D3D11_SUBRESOURCE_DATA starIndexBufferData;
	ZeroMemory(&starIndexBufferData, sizeof(starIndexBufferData));
	starIndexBufferData.pSysMem = starIndex;
	pDevice->CreateBuffer(&starIndexBufferDesc, &starIndexBufferData, &pStar_indexBuffer);

	//Heli

	//Create Heli Shaders
	pDevice->CreateVertexShader(Cube_VS, sizeof(Cube_VS), NULL, &pHeli_VSShader);
	pDevice->CreatePixelShader(Cube_PS, sizeof(Cube_PS), NULL, &pHeli_PSShader);
	pDevice->CreateVertexShader(SkyBox_VS, sizeof(SkyBox_VS), NULL, &pskybox_VSShader);
	pDevice->CreatePixelShader(SkyBox_PS, sizeof(SkyBox_PS), NULL, &pskybox_PSShader);


	thread load = thread(&DEMO::Load, this);
	load.join();


	//Load Quad
	quad_worldMatrix = XMMatrixIdentity();
	D3D11_BUFFER_DESC quadBufferDesc;
	ZeroMemory(&quadBufferDesc, sizeof(quadBufferDesc));
	quadBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
	quadBufferDesc.ByteWidth = sizeof(XMFLOAT4);
	quadBufferDesc.CPUAccessFlags = NULL;
	quadBufferDesc.Usage = D3D11_USAGE_IMMUTABLE;
	quadBufferDesc.MiscFlags = 0;
	quadBufferDesc.StructureByteStride = 0;
	D3D11_SUBRESOURCE_DATA quadData;
	ZeroMemory(&quadData, sizeof(quadData));
	quadData.pSysMem = &quad_pos;
	pDevice->CreateBuffer(&quadBufferDesc, &quadData, &pQuadBuffer);
	pDevice->CreateVertexShader(Quad_VS, sizeof(Quad_VS), NULL, &pQuad_VSShader);
	pDevice->CreateGeometryShader(Quad_GS, sizeof(Quad_GS), NULL, &pQuad_GSShader);
	pDevice->CreatePixelShader(Quad_PS, sizeof(Quad_PS), NULL, &pQuad_PSShader);

	D3D11_INPUT_ELEMENT_DESC quadInputLayout[] =
	{
		{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },

	};
	pDevice->CreateInputLayout(quadInputLayout, 1, Quad_VS, sizeof(Quad_VS), &pQuadInputLayout);


	//Load Cube
	D3D11_BUFFER_DESC cubeBufferDesc;
	ZeroMemory(&cubeBufferDesc, sizeof(cubeBufferDesc));
	cubeBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
	cubeBufferDesc.ByteWidth = sizeof(_OBJ_VERT_) * 776;
	cubeBufferDesc.CPUAccessFlags = NULL;
	cubeBufferDesc.Usage = D3D11_USAGE_IMMUTABLE;
	cubeBufferDesc.MiscFlags = 0;
	cubeBufferDesc.StructureByteStride = 0;
	D3D11_SUBRESOURCE_DATA cubeVerticesData;
	ZeroMemory(&cubeVerticesData, sizeof(cubeVerticesData));
	cubeVerticesData.pSysMem = Cube_data;
	pDevice->CreateBuffer(&cubeBufferDesc, &cubeVerticesData, &pCube);


	//Create Cube Shaders
	pDevice->CreateVertexShader(Projection_VS, sizeof(Projection_VS), NULL, &pProjection_VSShader);
	pDevice->CreatePixelShader(Trivial_PS, sizeof(Trivial_PS), NULL, &pCube_PSShader);

	//Create Cube InputLayout
	D3D11_INPUT_ELEMENT_DESC cubeInputLayout[] =
	{
		{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },
		{ "TEXCOORD", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },
		{ "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },
		{ "WORLD", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_INSTANCE_DATA, 1 },
		{ "WORLD", 1, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_INSTANCE_DATA, 1 },
		{ "WORLD", 2, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_INSTANCE_DATA, 1 },
		{ "WORLD", 3, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_INSTANCE_DATA, 1 },
	};
	pDevice->CreateInputLayout(cubeInputLayout, 7, Projection_VS, sizeof(Projection_VS), &pCube_inputLayout);



	//Create Cube Index Buffer
	D3D11_BUFFER_DESC cubeIndexBufferDesc;
	ZeroMemory(&cubeIndexBufferDesc, sizeof(cubeIndexBufferDesc));
	cubeIndexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
	cubeIndexBufferDesc.ByteWidth = sizeof(unsigned int) * 1692;
	cubeIndexBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
	cubeIndexBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
	cubeIndexBufferDesc.MiscFlags = 0;
	cubeIndexBufferDesc.StructureByteStride = 0;
	D3D11_SUBRESOURCE_DATA cubeIndexBufferData;
	ZeroMemory(&cubeIndexBufferData, sizeof(cubeIndexBufferData));
	cubeIndexBufferData.pSysMem = Cube_indicies;
	pDevice->CreateBuffer(&cubeIndexBufferDesc, &cubeIndexBufferData, &pCube_indexBuffer);

	//Instancing Cube

	XMFLOAT4X4 temp;
	/*for (size_t i = 0; i < 3; i++)
	{
		XMStoreFloat4x4(&temp, XMMatrixTranslation( 1.5f*cosf(i), 1.0f, 1.5f*sinf(i)));
		cubeInstancedData.push_back(temp);
	}*/

	XMStoreFloat4x4(&temp, XMMatrixTranslation(2.0f, 1.0f, 2.0f));
	cubeInstancedData.push_back(temp);
	XMStoreFloat4x4(&temp, XMMatrixTranslation(0.0f, 1.0f, 0.0f));
	cubeInstancedData.push_back(temp);
	XMStoreFloat4x4(&temp, XMMatrixTranslation(-2.0f, 1.0f, -2.0f));
	cubeInstancedData.push_back(temp);

	D3D11_BUFFER_DESC cubeInstanceBufferDESC;
	cubeInstanceBufferDESC.Usage = D3D11_USAGE_DYNAMIC;
	cubeInstanceBufferDESC.ByteWidth = sizeof(XMFLOAT4X4) * (unsigned int)cubeInstancedData.size();
	cubeInstanceBufferDESC.BindFlags = D3D11_BIND_VERTEX_BUFFER;
	cubeInstanceBufferDESC.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
	cubeInstanceBufferDESC.MiscFlags = 0;
	cubeInstanceBufferDESC.StructureByteStride = 0;
	D3D11_SUBRESOURCE_DATA instData;
	ZeroMemory(&instData, sizeof(instData));
	instData.pSysMem = cubeInstancedData.data();
	pDevice->CreateBuffer(&cubeInstanceBufferDESC, &instData, &pCubeInstanceBuffer);


	//Create Constant buffer
	D3D11_BUFFER_DESC constbufferObjectDesc;
	ZeroMemory(&constbufferObjectDesc, sizeof(constbufferObjectDesc));
	constbufferObjectDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
	constbufferObjectDesc.ByteWidth = sizeof(XMMATRIX);
	constbufferObjectDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
	constbufferObjectDesc.Usage = D3D11_USAGE_DYNAMIC;
	constbufferObjectDesc.MiscFlags = 0;
	constbufferObjectDesc.StructureByteStride = 0;
	pDevice->CreateBuffer(&constbufferObjectDesc, NULL, &pConstantObjectBuffer);

	D3D11_BUFFER_DESC constbufferStarDesc;
	ZeroMemory(&constbufferStarDesc, sizeof(constbufferStarDesc));
	constbufferStarDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
	constbufferStarDesc.ByteWidth = sizeof(XMMATRIX);
	constbufferStarDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
	constbufferStarDesc.Usage = D3D11_USAGE_DYNAMIC;
	constbufferStarDesc.MiscFlags = 0;
	constbufferStarDesc.StructureByteStride = 0;
	pDevice->CreateBuffer(&constbufferStarDesc, NULL, &pConstantStarBuffer);

	D3D11_BUFFER_DESC constbufferSceneDesc;
	ZeroMemory(&constbufferSceneDesc, sizeof(constbufferSceneDesc));
	constbufferSceneDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
	constbufferSceneDesc.ByteWidth = sizeof(Scene);
	constbufferSceneDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
	constbufferSceneDesc.Usage = D3D11_USAGE_DYNAMIC;
	constbufferSceneDesc.MiscFlags = 0;
	constbufferSceneDesc.StructureByteStride = 0;
	pDevice->CreateBuffer(&constbufferSceneDesc, NULL, &pConstantSceneBuffer);

	D3D11_BUFFER_DESC constbufferQuadDesc;
	ZeroMemory(&constbufferQuadDesc, sizeof(constbufferQuadDesc));
	constbufferQuadDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
	constbufferQuadDesc.ByteWidth = sizeof(Scene);
	constbufferQuadDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
	constbufferQuadDesc.Usage = D3D11_USAGE_DYNAMIC;
	constbufferQuadDesc.MiscFlags = 0;
	constbufferQuadDesc.StructureByteStride = 0;
	pDevice->CreateBuffer(&constbufferQuadDesc, NULL, &pConstantQuadBuffer);


	D3D11_BUFFER_DESC constbufferTimeDesc;
	ZeroMemory(&constbufferTimeDesc, sizeof(constbufferTimeDesc));
	constbufferTimeDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
	constbufferTimeDesc.ByteWidth = sizeof(float) * 4;
	constbufferTimeDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
	constbufferTimeDesc.Usage = D3D11_USAGE_DYNAMIC;
	constbufferTimeDesc.MiscFlags = 0;
	constbufferTimeDesc.StructureByteStride = 0;
	pDevice->CreateBuffer(&constbufferTimeDesc, NULL, &pConstantTimeBuffer);



	//Create Cube Texture Sampler
	D3D11_SAMPLER_DESC cubeTextureSamplerDESC;
	ZeroMemory(&cubeTextureSamplerDESC, sizeof(cubeTextureSamplerDESC));
	cubeTextureSamplerDESC.Filter = D3D11_FILTER_ANISOTROPIC;
	cubeTextureSamplerDESC.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
	cubeTextureSamplerDESC.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
	cubeTextureSamplerDESC.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
	cubeTextureSamplerDESC.ComparisonFunc = D3D11_COMPARISON_NEVER;
	cubeTextureSamplerDESC.MinLOD = 0;
	cubeTextureSamplerDESC.MaxLOD = D3D11_FLOAT32_MAX;

	pDevice->CreateSamplerState(&cubeTextureSamplerDESC, &pCubeTextureSampler);



	//Create Cube RasterState
	D3D11_RASTERIZER_DESC cubeRasterDESC;
	ZeroMemory(&cubeRasterDESC, sizeof(cubeRasterDESC));
	cubeRasterDESC.AntialiasedLineEnable = true;
	cubeRasterDESC.FillMode = D3D11_FILL_SOLID;
	cubeRasterDESC.CullMode = D3D11_CULL_FRONT;
	pDevice->CreateRasterizerState(&cubeRasterDESC, &pCubeRSf);

	ZeroMemory(&cubeRasterDESC, sizeof(cubeRasterDESC));
	cubeRasterDESC.AntialiasedLineEnable = true;
	cubeRasterDESC.FillMode = D3D11_FILL_SOLID;
	cubeRasterDESC.CullMode = D3D11_CULL_BACK;
	pDevice->CreateRasterizerState(&cubeRasterDESC, &pCubeRSb);


	//Create Blend State
	D3D11_BLEND_DESC blendDESC;
	ZeroMemory(&blendDESC, sizeof(blendDESC));
	blendDESC.AlphaToCoverageEnable = true;
	blendDESC.RenderTarget[0].BlendEnable = true;
	blendDESC.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;
	blendDESC.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE;
	blendDESC.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
	blendDESC.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO;
	blendDESC.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
	blendDESC.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
	blendDESC.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;

	pDevice->CreateBlendState(&blendDESC, &pBlendState);


	GetCursorPos(&lastPos);
	cube_matrix = XMMatrixTranslation(0.0f, 0.0f, 5.0f);
	star_matrix = XMMatrixScaling(1.0f, 1.0f, 1.0f) * XMMatrixTranslation(0.0f, 0.5f, 5.0f);

	another_camera.UpdateProjection(60.0f, (float)swapchain_DESC.BufferDesc.Width / (float)2, (float)swapchain_DESC.BufferDesc.Height, NEAR_PLANE, FAR_PLANE);
	another_camera.SetPosition({ 10.0f, 1.0f, 0.0f });
	another_camera.RotateY(-90.0f);
	another_camera.UpdateView();
	camera.UpdateProjection(60.0f, (float)swapchain_DESC.BufferDesc.Width / (float)2, (float)swapchain_DESC.BufferDesc.Height, NEAR_PLANE, FAR_PLANE);
	heli.GO_worldMatrix = XMMatrixScaling(0.1f, 0.1f, 0.1f) *XMMatrixTranslation(0.0f, 5.0f, 0.0f);
	ground.GO_worldMatrix = XMMatrixTranslation(0.0f, -1.0f, 0.0f);
	skybox.GO_worldMatrix = XMMatrixIdentity();
	parkLight.GO_worldMatrix = XMMatrixTranslation(0.0f, -1.0f, 0.0f);

	//Lights
	allLights.amLight.lightColor = { 0.58f, 0.58f, 0.58f,1.0f };
	allLights.dLight.lightColor = { 1.0f, 1.0f, 1.0f,1.0f };
	allLights.dLight.lightDirection = { 0.58f, -0.58f, 0.58f,1.0f };
	allLights.pLight.lightColor = { 0.0f,1.0f,0.0f,1.0f };
	allLights.pLight.lightPosition = { 5.0f,3.0f,0.0f,1.0f };
	allLights.sLight.lightPosition = { camera.GetPosition().x,camera.GetPosition().y,camera.GetPosition().z,1.0f };
	allLights.sLight.lightColor = { 0.0f,0.0f,1.0f,1.0f };
	allLights.sLight.coneDirAndRatio = { camera.GetForward().x,camera.GetForward().y,camera.GetForward().z,0.8f };


	//Light Constant Buffer
	D3D11_BUFFER_DESC constbufferLightDesc;
	ZeroMemory(&constbufferLightDesc, sizeof(constbufferLightDesc));
	constbufferLightDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
	constbufferLightDesc.ByteWidth = sizeof(allLights);
	constbufferLightDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
	constbufferLightDesc.Usage = D3D11_USAGE_DYNAMIC;
	constbufferLightDesc.MiscFlags = 0;
	constbufferLightDesc.StructureByteStride = 0;
	pDevice->CreateBuffer(&constbufferLightDesc, NULL, &pLightingBuffer);


	scene.percent = 0.0f;
}
コード例 #5
0
	void D3D9RenderWindow::create(const String& name, unsigned int width, unsigned int height,
		bool fullScreen, const NameValuePairList *miscParams)
	{
		HINSTANCE hInst = mInstance;
	
		HWND parentHWnd = 0;
		HWND externalHandle = 0;
		mFSAAType = D3DMULTISAMPLE_NONE;
		mFSAAQuality = 0;
		mFSAA = 0;
		mVSync = false;
		mVSyncInterval = 1;
		String title = name;
		unsigned int colourDepth = 32;
		int left = INT_MAX; // Defaults to screen center
		int top = INT_MAX;  // Defaults to screen center
		bool depthBuffer = true;
		String border = "";
		bool outerSize = false;
		mUseNVPerfHUD = false;
		size_t fsaaSamples = 0;
		String fsaaHint;
		int monitorIndex = -1;	//Default by detecting the adapter from left / top position

		if(miscParams)
		{
			// Get variable-length params
			NameValuePairList::const_iterator opt;
			// left (x)
			opt = miscParams->find("left");
			if(opt != miscParams->end())
				left = StringConverter::parseInt(opt->second);
			// top (y)
			opt = miscParams->find("top");
			if(opt != miscParams->end())
				top = StringConverter::parseInt(opt->second);
			// Window title
			opt = miscParams->find("title");
			if(opt != miscParams->end())
				title = opt->second;
			// parentWindowHandle		-> parentHWnd
			opt = miscParams->find("parentWindowHandle");
			if(opt != miscParams->end())
				parentHWnd = (HWND)StringConverter::parseUnsignedInt(opt->second);
			// externalWindowHandle		-> externalHandle
			opt = miscParams->find("externalWindowHandle");
			if(opt != miscParams->end())
				externalHandle = (HWND)StringConverter::parseUnsignedInt(opt->second);
			// vsync	[parseBool]
			opt = miscParams->find("vsync");
			if(opt != miscParams->end())
				mVSync = StringConverter::parseBool(opt->second);
			// vsyncInterval	[parseUnsignedInt]
			opt = miscParams->find("vsyncInterval");
			if(opt != miscParams->end())
				mVSyncInterval = StringConverter::parseUnsignedInt(opt->second);
			// displayFrequency
			opt = miscParams->find("displayFrequency");
			if(opt != miscParams->end())
				mDisplayFrequency = StringConverter::parseUnsignedInt(opt->second);
			// colourDepth
			opt = miscParams->find("colourDepth");
			if(opt != miscParams->end())
				colourDepth = StringConverter::parseUnsignedInt(opt->second);
			// depthBuffer [parseBool]
			opt = miscParams->find("depthBuffer");
			if(opt != miscParams->end())
				depthBuffer = StringConverter::parseBool(opt->second);
			// FSAA settings
			opt = miscParams->find("FSAA");
			if(opt != miscParams->end())
			{
				mFSAA = StringConverter::parseUnsignedInt(opt->second);
			}
			opt = miscParams->find("FSAAHint");
			if(opt != miscParams->end())
			{
				mFSAAHint = opt->second;
			}

			// window border style
			opt = miscParams->find("border");
			if(opt != miscParams->end())
				border = opt->second;
			// set outer dimensions?
			opt = miscParams->find("outerDimensions");
			if(opt != miscParams->end())
				outerSize = StringConverter::parseBool(opt->second);
			// NV perf HUD?
			opt = miscParams->find("useNVPerfHUD");
			if(opt != miscParams->end())
				mUseNVPerfHUD = StringConverter::parseBool(opt->second);
			// sRGB?
			opt = miscParams->find("gamma");
			if(opt != miscParams->end())
				mHwGamma = StringConverter::parseBool(opt->second);
			// monitor index
			opt = miscParams->find("monitorIndex");
			if(opt != miscParams->end())
				monitorIndex = StringConverter::parseInt(opt->second);

		}

		// Destroy current window if any
		if( mHWnd )
			destroy();

		if (!externalHandle)
		{
			DWORD		dwStyle = WS_VISIBLE | WS_CLIPCHILDREN;
			DWORD		dwStyleEx = 0;
			HMONITOR    hMonitor = NULL;		
			MONITORINFO monitorInfo;
			RECT		rc;


			// If we specified which adapter we want to use - find it's monitor.
			if (monitorIndex != -1)
			{
				IDirect3D9* direct3D9 = D3D9RenderSystem::getDirect3D9();

				for (uint i=0; i < direct3D9->GetAdapterCount(); ++i)
				{
					if (i == monitorIndex)
					{
						hMonitor = direct3D9->GetAdapterMonitor(i);
						break;
					}
				}				
			}

			// If we didn't specified the adapter index, or if it didn't find it
			if (hMonitor == NULL)
			{
				POINT windowAnchorPoint;

				// Fill in anchor point.
				windowAnchorPoint.x = left;
				windowAnchorPoint.y = top;


				// Get the nearest monitor to this window.
				hMonitor = MonitorFromPoint(windowAnchorPoint, MONITOR_DEFAULTTONEAREST);
			}

			// Get the target monitor info		
			memset(&monitorInfo, 0, sizeof(MONITORINFO));
			monitorInfo.cbSize = sizeof(MONITORINFO);
			GetMonitorInfo(hMonitor, &monitorInfo);


			unsigned int winWidth, winHeight;
			winWidth = width;
			winHeight = height;
			if (!fullScreen)
				adjustWindow(width, height, &winWidth, &winHeight);


			// No specified top left -> Center the window in the middle of the monitor
			if (left == INT_MAX || top == INT_MAX)
			{				
				int screenw = monitorInfo.rcWork.right  - monitorInfo.rcWork.left;
				int screenh = monitorInfo.rcWork.bottom - monitorInfo.rcWork.top;

				// clamp window dimensions to screen size
				int outerw = (winWidth < screenw)? winWidth : screenw;
				int outerh = (winHeight < screenh)? winHeight : screenh;

				if (left == INT_MAX)
					left = monitorInfo.rcWork.left + (screenw - outerw) / 2;
				else if (monitorIndex != -1)
					left += monitorInfo.rcWork.left;

				if (top == INT_MAX)
					top = monitorInfo.rcWork.top + (screenh - outerh) / 2;
				else if (monitorIndex != -1)
					top += monitorInfo.rcWork.top;
			}
			else if (monitorIndex != -1)
			{
				left += monitorInfo.rcWork.left;
				top += monitorInfo.rcWork.top;
			}

			mWidth = mDesiredWidth = width;
			mHeight = mDesiredHeight = height;
			mTop = top;
			mLeft = left;

			if (fullScreen)
			{
				dwStyleEx |= WS_EX_TOPMOST;
				dwStyle |= WS_POPUP;
				mTop = monitorInfo.rcMonitor.top;
				mLeft = monitorInfo.rcMonitor.left;		
			}
			else
			{
				if (parentHWnd)
				{
					dwStyle |= WS_CHILD;
				}
				else
				{
					if (border == "none")
						dwStyle |= WS_POPUP;
					else if (border == "fixed")
						dwStyle |= WS_OVERLAPPED | WS_BORDER | WS_CAPTION |
						WS_SYSMENU | WS_MINIMIZEBOX;
					else
						dwStyle |= WS_OVERLAPPEDWINDOW;
				}

				if (!outerSize)
				{
					// Calculate window dimensions required
					// to get the requested client area
					SetRect(&rc, 0, 0, mWidth, mHeight);
					AdjustWindowRect(&rc, dwStyle, false);
					mWidth = rc.right - rc.left;
					mHeight = rc.bottom - rc.top;

					// Clamp window rect to the nearest display monitor.
					if (mLeft < monitorInfo.rcWork.left)
						mLeft = monitorInfo.rcWork.left;		

					if (mTop < monitorInfo.rcWork.top)					
						mTop = monitorInfo.rcWork.top;					
				
					if (static_cast<int>(winWidth) > monitorInfo.rcWork.right - mLeft)					
						winWidth = monitorInfo.rcWork.right - mLeft;	

					if (static_cast<int>(winHeight) > monitorInfo.rcWork.bottom - mTop)					
						winHeight = monitorInfo.rcWork.bottom - mTop;										
				}
			}
			

			// Register the window class
			// NB allow 4 bytes of window data for D3D9RenderWindow pointer
			WNDCLASS wc = { 0, WindowEventUtilities::_WndProc, 0, 0, hInst,
				LoadIcon(0, IDI_APPLICATION), LoadCursor(NULL, IDC_ARROW),
				(HBRUSH)GetStockObject(BLACK_BRUSH), 0, "OgreD3D9Wnd" };
			RegisterClass(&wc);

			// Create our main window
			// Pass pointer to self
			mIsExternal = false;
			mHWnd = CreateWindowEx(dwStyleEx, "OgreD3D9Wnd", title.c_str(), dwStyle,
				mLeft, mTop, winWidth, winHeight, parentHWnd, 0, hInst, this);

			WindowEventUtilities::_addRenderWindow(this);
		}
		else
		{
			mHWnd = externalHandle;
			mIsExternal = true;
		}

		RECT rc;
		// top and left represent outer window coordinates
		GetWindowRect(mHWnd, &rc);
		mTop = rc.top;
		mLeft = rc.left;
		// width and height represent interior drawable area
		GetClientRect(mHWnd, &rc);
		mWidth = rc.right;
		mHeight = rc.bottom;

		mName = name;
		mDepthBufferPoolId = depthBuffer ? DepthBuffer::POOL_DEFAULT : DepthBuffer::POOL_NO_DEPTH;
		mDepthBuffer = 0;
		mIsFullScreen = fullScreen;
		mColourDepth = colourDepth;

		LogManager::getSingleton().stream()
			<< "D3D9 : Created D3D9 Rendering Window '"
			<< mName << "' : " << mWidth << "x" << mHeight 
			<< ", " << mColourDepth << "bpp";
									
		mActive = true;
		mClosed = false;
	}
コード例 #6
0
CWindowsToolkit::CWindowsToolkit(void *parentWindow, CEditor *editor)
{
    this->parentWindow  = parentWindow;
    this->editor        = editor;

    g_useCount++;
    if (g_useCount == 1)
    {
        WNDCLASSW windowClass;
        windowClass.style         = CS_DBLCLKS;
        windowClass.lpfnWndProc   = WindowProc;
        windowClass.cbClsExtra    = 0;
        windowClass.cbWndExtra    = 0;
        windowClass.hInstance     = (HINSTANCE)hInstance;
        windowClass.hIcon         = LoadIcon((HINSTANCE)hInstance,MAKEINTRESOURCE(IDI_ICON));
        windowClass.hCursor       = LoadCursor( NULL, IDC_ARROW );
        windowClass.hbrBackground = NULL;
        windowClass.lpszMenuName  = 0;
        windowClass.lpszClassName = L"OxeVstEditorClass";
        RegisterClassW(&windowClass);
    }

    if (!parentWindow)
    {
        RECT rect;
        rect.left   = 100;
        rect.top    = 100;
        rect.right  = GUI_WIDTH;
        rect.bottom = GUI_HEIGHT;
        AdjustWindowRect(&rect, WS_SYSMENU | WS_CAPTION, FALSE);
        rect.bottom += GetSystemMetrics(SM_CYCAPTION);
        rect.bottom += GetSystemMetrics(SM_CYFIXEDFRAME);
        rect.right  += GetSystemMetrics(SM_CXFIXEDFRAME);

        this->hWnd = CreateWindowW
        (
            L"OxeVstEditorClass",
            L"",
            WS_SYSMENU | WS_CAPTION | WS_MINIMIZEBOX,
            rect.left,
            rect.top,
            rect.right,
            rect.bottom,
            0,
            0,
            (HINSTANCE)hInstance,
            NULL
        );
    }
    else
    {
        this->hWnd = CreateWindowExW
        (
            0,
            L"OxeVstEditorClass",
            L"",
            WS_CHILD | WS_VISIBLE,
            0,
            0,
            GUI_WIDTH,
            GUI_HEIGHT,
            (HWND)parentWindow,
            NULL,
            (HINSTANCE)hInstance,
            NULL
        );
    }

#ifdef _WIN64
    SetWindowLongPtr(hWnd, GWLP_USERDATA, (LONG_PTR)this);
#else
    SetWindowLong(hWnd, GWL_USERDATA, (LONG)this);
#endif

    // load resources
    char path[MAX_PATH];
    GetResourcesPath(path, MAX_PATH);

    char fullPath[MAX_PATH];
    StringCchPrintf(fullPath, MAX_PATH, "%s\\%s", path, "chars.bmp");
    bmps[BMP_CHARS]   = (HBITMAP)LoadImageA(NULL, fullPath, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
    StringCchPrintf(fullPath, MAX_PATH, "%s\\%s", path, "knob.bmp");
    bmps[BMP_KNOB]    = (HBITMAP)LoadImageA(NULL, fullPath, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
    StringCchPrintf(fullPath, MAX_PATH, "%s\\%s", path, "knob2.bmp");
    bmps[BMP_KNOB2]   = (HBITMAP)LoadImageA(NULL, fullPath, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
    StringCchPrintf(fullPath, MAX_PATH, "%s\\%s", path, "knob3.bmp");
    bmps[BMP_KNOB3]   = (HBITMAP)LoadImageA(NULL, fullPath, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
    StringCchPrintf(fullPath, MAX_PATH, "%s\\%s", path, "key.bmp");
    bmps[BMP_KEY]     = (HBITMAP)LoadImageA(NULL, fullPath, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
    StringCchPrintf(fullPath, MAX_PATH, "%s\\%s", path, "bg.bmp");
    bmps[BMP_BG]      = (HBITMAP)LoadImageA(NULL, fullPath, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
    StringCchPrintf(fullPath, MAX_PATH, "%s\\%s", path, "buttons.bmp");
    bmps[BMP_BUTTONS] = (HBITMAP)LoadImageA(NULL, fullPath, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
    StringCchPrintf(fullPath, MAX_PATH, "%s\\%s", path, "ops.bmp");
    bmps[BMP_OPS]     = (HBITMAP)LoadImageA(NULL, fullPath, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
    
    if (!bmps[BMP_CHARS  ]) bmps[BMP_CHARS  ] = LoadBitmap((HINSTANCE)hInstance,MAKEINTRESOURCE(IDB_CHARS));
    if (!bmps[BMP_KNOB   ]) bmps[BMP_KNOB   ] = LoadBitmap((HINSTANCE)hInstance,MAKEINTRESOURCE(IDB_KNOB));
    if (!bmps[BMP_KNOB2  ]) bmps[BMP_KNOB2  ] = LoadBitmap((HINSTANCE)hInstance,MAKEINTRESOURCE(IDB_KNOB2));
    if (!bmps[BMP_KNOB3  ]) bmps[BMP_KNOB3  ] = LoadBitmap((HINSTANCE)hInstance,MAKEINTRESOURCE(IDB_KNOB3));
    if (!bmps[BMP_KEY    ]) bmps[BMP_KEY    ] = LoadBitmap((HINSTANCE)hInstance,MAKEINTRESOURCE(IDB_CHAVE));
    if (!bmps[BMP_BG     ]) bmps[BMP_BG     ] = LoadBitmap((HINSTANCE)hInstance,MAKEINTRESOURCE(IDB_FUNDO));
    if (!bmps[BMP_BUTTONS]) bmps[BMP_BUTTONS] = LoadBitmap((HINSTANCE)hInstance,MAKEINTRESOURCE(IDB_BUTTONS));
    if (!bmps[BMP_OPS    ]) bmps[BMP_OPS    ] = LoadBitmap((HINSTANCE)hInstance,MAKEINTRESOURCE(IDB_OPS));
    // create offscreen buffer
    hdc = GetDC(hWnd);
    hdcMem = CreateCompatibleDC(hdc);
    hdcAux = CreateCompatibleDC(hdc);
    bitmap = CreateCompatibleBitmap(hdc, GUI_WIDTH, GUI_HEIGHT);
    SelectObject(hdcMem, bitmap);
    SetTimer(hWnd, 0, TIMER_RESOLUTION_MS, NULL);
}
コード例 #7
0
static int window_init( WININFO *info )
{
	unsigned int	PixelFormat;
    DWORD			dwExStyle, dwStyle;
    DEVMODE			dmScreenSettings;
	RECT			rec;

    WNDCLASS		wc;

    ZeroMemory( &wc, sizeof(WNDCLASS) );
    wc.style         = CS_OWNDC|CS_HREDRAW|CS_VREDRAW;
    wc.lpfnWndProc   = WndProc;
    wc.hInstance     = info->hInstance;
    wc.lpszClassName = info->wndclass;
	
    if( !RegisterClass(&wc) )
        return( 0 );

    if( info->full )
    {
        dmScreenSettings.dmSize       = sizeof(DEVMODE);
        dmScreenSettings.dmFields     = DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT;
        dmScreenSettings.dmBitsPerPel = 24;
        dmScreenSettings.dmPelsWidth  = XRES;
        dmScreenSettings.dmPelsHeight = YRES;
        if( ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL)
            return( 0 );
        dwExStyle = WS_EX_APPWINDOW;
        dwStyle   = WS_VISIBLE | WS_POPUP;// | WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
		ShowCursor( 0 );
    }
    else
    {
        dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
        dwStyle   = WS_VISIBLE | WS_CAPTION | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_SYSMENU;
    }

    rec.left   = 0;
    rec.top    = 0;
    rec.right  = XRES;
    rec.bottom = YRES;
    AdjustWindowRect( &rec, dwStyle, 0 );
	windowRect.left = 0;
	windowRect.top = 0;
	windowRect.right = XRES;
	windowRect.bottom = YRES;

    info->hWnd = CreateWindowEx( dwExStyle, wc.lpszClassName, "live coding", dwStyle,
                               (GetSystemMetrics(SM_CXSCREEN)-rec.right+rec.left)>>1,
                               (GetSystemMetrics(SM_CYSCREEN)-rec.bottom+rec.top)>>1,
                               rec.right-rec.left, rec.bottom-rec.top, 0, 0, info->hInstance, 0 );
    if( !info->hWnd )
        return( 0 );

    if( !(info->hDC=GetDC(info->hWnd)) )
        return( 0 );

    if( !(PixelFormat=ChoosePixelFormat(info->hDC,&pfd)) )
        return( 0 );

    if( !SetPixelFormat(info->hDC,PixelFormat,&pfd) )
        return( 0 );

    if( !(info->hRC=wglCreateContext(info->hDC)) )
        return( 0 );

    if( !wglMakeCurrent(info->hDC,info->hRC) )
        return( 0 );
    
    return( 1 );
}
コード例 #8
0
ファイル: GraphicsWindow.cpp プロジェクト: AratnitY/stepmania
/* Set the final window size, set the window text and icon, and then unhide the
 * window. */
void GraphicsWindow::CreateGraphicsWindow( const VideoModeParams &p, bool bForceRecreateWindow )
{
	g_CurrentParams = p;

	// Adjust g_CurrentParams to reflect the actual display settings.
	AdjustVideoModeParams( g_CurrentParams );

	if( g_hWndMain == NULL || bForceRecreateWindow )
	{
		int iWindowStyle = GetWindowStyle( p.windowed );

		AppInstance inst;
		HWND hWnd = CreateWindow( g_sClassName, "app", iWindowStyle,
						0, 0, 0, 0, NULL, NULL, inst, NULL );
		if( hWnd == NULL )
			RageException::Throw( "%s", werr_ssprintf( GetLastError(), "CreateWindow" ).c_str() );

		/* If an old window exists, transfer focus to the new window before
		 * deleting it, or some other window may temporarily get focus, which
		 * can cause it to be resized. */
		if( g_hWndMain != NULL )
		{
			// While we change to the new window, don't do ChangeDisplaySettings in WM_ACTIVATE.
			g_bRecreatingVideoMode = true;
			SetForegroundWindow( hWnd );
			g_bRecreatingVideoMode = false;

			GraphicsWindow::DestroyGraphicsWindow();
		}

		g_hWndMain = hWnd;
		CrashHandler::SetForegroundWindow( g_hWndMain );
		g_HDC = GetDC( g_hWndMain );
	}

	// Update the window title.
	do
	{
		if( m_bWideWindowClass )
		{
			if( SetWindowText( g_hWndMain, ConvertUTF8ToACP(p.sWindowTitle).c_str() ) )
				break;
		}

		SetWindowTextA( g_hWndMain, ConvertUTF8ToACP(p.sWindowTitle) );
	} while(0);

	// Update the window icon.
	if( g_hIcon != NULL )
	{
		SetClassLong( g_hWndMain, GCL_HICON, (LONG) LoadIcon(NULL,IDI_APPLICATION) );
		DestroyIcon( g_hIcon );
		g_hIcon = NULL;
	}
	g_hIcon = IconFromFile( p.sIconFile );
	if( g_hIcon != NULL )
		SetClassLong( g_hWndMain, GCL_HICON, (LONG) g_hIcon );

	/* The window style may change as a result of switching to or from fullscreen;
	 * apply it. Don't change the WS_VISIBLE bit. */
	int iWindowStyle = GetWindowStyle( p.windowed );
	if( GetWindowLong( g_hWndMain, GWL_STYLE ) & WS_VISIBLE )
		iWindowStyle |= WS_VISIBLE;
	SetWindowLong( g_hWndMain, GWL_STYLE, iWindowStyle );

	RECT WindowRect;
	SetRect( &WindowRect, 0, 0, p.width, p.height );
	AdjustWindowRect( &WindowRect, iWindowStyle, FALSE );

	//LOG->Warn( "w = %d, h = %d", p.width, p.height );

	const int iWidth = WindowRect.right - WindowRect.left;
	const int iHeight = WindowRect.bottom - WindowRect.top;

	// If windowed, center the window.
	int x = 0, y = 0;
	if( p.windowed )
	{
		x = GetSystemMetrics(SM_CXSCREEN)/2-iWidth/2;
		y = GetSystemMetrics(SM_CYSCREEN)/2-iHeight/2;
	}

	/* Move and resize the window. SWP_FRAMECHANGED causes the above
	 * SetWindowLong to take effect. */
	if( !SetWindowPos( g_hWndMain, HWND_NOTOPMOST, x, y, iWidth, iHeight, SWP_FRAMECHANGED|SWP_SHOWWINDOW ) )
		LOG->Warn( "%s", werr_ssprintf( GetLastError(), "SetWindowPos" ).c_str() );

	SetForegroundWindow( g_hWndMain );

	/* Pump messages quickly, to make sure the window is completely set up.
	 * If we don't do this, then starting up in a D3D fullscreen window may
	 * cause all other windows on the system to be resized. */
	MSG msg;
	while( PeekMessage( &msg, NULL, 0, 0, PM_NOREMOVE ) )
	{
		GetMessage( &msg, NULL, 0, 0 );
		DispatchMessage( &msg );
	}
}
int main()
{
	OnStart( "." );

	const char WinName[] = "MyWin";

	WNDCLASS wcl;
	memset( &wcl, 0, sizeof( WNDCLASS ) );
	wcl.lpszClassName = WinName;
	wcl.lpfnWndProc = MyFunc;
	wcl.hCursor = LoadCursor( NULL, IDC_ARROW );

	if ( !RegisterClass( &wcl ) ) { return 0; }

	RECT Rect;

	Rect.left = 0;
	Rect.top = 0;
	Rect.right  = ImageWidth;
	Rect.bottom = ImageHeight;

	DWORD dwStyle = WS_OVERLAPPEDWINDOW;

	AdjustWindowRect( &Rect, dwStyle, false );

	int WinWidth  = Rect.right  - Rect.left;
	int WinHeight = Rect.bottom - Rect.top;

	HWND hWnd = CreateWindowA( WinName, "App8", dwStyle, 100, 100, WinWidth, WinHeight, 0, NULL, NULL, NULL );

	ShowWindow( hWnd, SW_SHOW );

	HDC dc = GetDC( hWnd );

	// Create the offscreen device context and buffer
	hMemDC = CreateCompatibleDC( dc );
	hTmpBmp = CreateCompatibleBitmap( dc, ImageWidth, ImageHeight );

	// filling the RGB555 bitmap header
	memset( &BitmapInfo.bmiHeader, 0, sizeof( BITMAPINFOHEADER ) );
	BitmapInfo.bmiHeader.biSize = sizeof( BITMAPINFOHEADER );
	BitmapInfo.bmiHeader.biWidth = ImageWidth;
	BitmapInfo.bmiHeader.biHeight = ImageHeight;
	BitmapInfo.bmiHeader.biPlanes = 1;
	BitmapInfo.bmiHeader.biBitCount = 32;
	BitmapInfo.bmiHeader.biSizeImage = ImageWidth * ImageHeight * 4;

	UpdateWindow( hWnd );

	MSG msg;

	SetTimer( hWnd, 1, 10, NULL );

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

	DeleteDC( hMemDC );
	DeleteObject( hTmpBmp );
	free( g_FrameBuffer );

	return msg.wParam;
}
コード例 #10
0
ファイル: ThisApp.cpp プロジェクト: profile1p/RubyGM
// 初始化ThisApp
HRESULT ThisApp::Initialize(){
	WNDCLASS wc;

	ZeroMemory(&wc, sizeof(wc));
	wc.hbrBackground = (HBRUSH)(COLOR_3DFACE + 1);
	wc.style = CS_HREDRAW | CS_VREDRAW;
	wc.cbWndExtra = DLGWINDOWEXTRA;
	wc.hInstance = HINST_THISCOMPONENT;
	wc.hCursor = LoadCursor(NULL, IDC_ARROW);
	wc.hIcon = LoadIconW(HINST_THISCOMPONENT, MAKEINTRESOURCE(IDI_APP_ICON));
	wc.lpfnWndProc = ThisApp::WndProc;
	wc.lpszClassName = AppInfo::APP_WINDOW_CLASS_NAME;
	wc.cbWndExtra = sizeof(LONG_PTR);
	RegisterClass(&wc);
	// 读取ini文件
	RECT window_rect = { 0, 0, AppInfo::SHOW_WIDTH, AppInfo::SHOW_HEIGHT };
	wchar_t title[32];
	DWORD rc = GetPrivateProfileStringW(L"Game", L"title", L"", title, sizeof title, L".\\Game.ini");
	if (rc){
		char buffer[8];
		if (GetPrivateProfileStringA("Game", "width", "", buffer, sizeof buffer, ".\\Game.ini"))
			window_rect.right = atoi(buffer);
		
		if (GetPrivateProfileStringA("Game", "height", "", buffer, sizeof buffer, ".\\Game.ini"))
			window_rect.bottom = atoi(buffer);
		
	}
	else
		wcscpy_s(title, AppInfo::APP_WINDOW_TITLE_NAME);
	// 调整窗口大小
	DWORD window_style = WS_CAPTION | WS_VISIBLE | WS_POPUP | WS_SYSMENU | WS_MINIMIZEBOX;
	AdjustWindowRect(&window_rect, window_style, FALSE);
	window_rect.right -= window_rect.left;
	window_rect.bottom -= window_rect.top;
	window_rect.left = (GetSystemMetrics(SM_CXFULLSCREEN) - window_rect.right) / 2;
	window_rect.top = (GetSystemMetrics(SM_CYFULLSCREEN) - window_rect.right) / 2;
	//window_rect.right += window_rect.left;
	//window_rect.bottom += window_rect.top;
	// 创建窗口
	m_hwnd = CreateWindowW(wc.lpszClassName, title, window_style,
		window_rect.left, window_rect.top, window_rect.right, window_rect.bottom, 0, 0, HINST_THISCOMPONENT, this);
	// 显示窗口
	if (m_hwnd){
		::GetClientRect(m_hwnd, &window_rect);
#ifdef _DEBUG
		_cwprintf(L"Window: %4d, %4d\n", window_rect.right, window_rect.bottom);
#endif
		ClientToScreen(m_hwnd, (LPPOINT)(&window_rect));
		window_rect.right += window_rect.left;
		window_rect.bottom += window_rect.top;
		ShowWindow(m_hwnd, SW_NORMAL);
		UpdateWindow(m_hwnd);
		// 设定并初始化渲染
		HRESULT hr = m_imageRender.SetHwnd(m_hwnd);
		if (SUCCEEDED(hr)){
			// 成功的话,创建渲染线程
			m_pRenderThread = (std::thread*)MPool.Alloc(sizeof std::thread);
			// 检查指针
			hr = m_pRenderThread ? S_OK : E_OUTOFMEMORY;
		}
		if (SUCCEEDED(hr)){
			// 显式析构
			new(m_pRenderThread) std::thread(ImageRender::RenderThread, &m_imageRender);
			// 成功的话,创建游戏逻辑线程
			m_pGameLogicThread = (std::thread*)MPool.Alloc(sizeof std::thread);
			// 检查指针
			hr = m_pGameLogicThread ? S_OK : E_OUTOFMEMORY;
			// 隐藏鼠标
			//::ShowCursor(FALSE);
			//ClipCursor(&window_rect);
		}
		if (SUCCEEDED(hr)){
			// 显式析构
			new(m_pGameLogicThread)std::thread(Game::LogicThread, m_hwnd);
			// 初始化输入接口
			hr = KMInput.Init(HINST_THISCOMPONENT, m_hwnd);
		}
		return hr;
	}
	return E_FAIL;
}
コード例 #11
0
ファイル: win_glw.c プロジェクト: cfr/qfusion
static void VID_SetWindowSize( bool fullscreen )
{
	RECT r;
	int stylebits;
	int exstyle;
	int x = glw_state.win_x, y = glw_state.win_y;
	int width = glConfig.width, height = glConfig.height;
	HWND parentHWND = glw_state.parenthWnd;

	if( fullscreen )
	{
		exstyle = WS_EX_TOPMOST;
		stylebits = ( WS_POPUP|WS_VISIBLE );
		parentHWND = NULL;
	}
	else if( parentHWND )
	{
		exstyle = 0;
		stylebits = WS_CHILD|WS_CLIPSIBLINGS|WS_CLIPCHILDREN|WS_VISIBLE;
	}
	else
	{
		exstyle = 0;
		stylebits = WINDOW_STYLE;
	}

	r.left = 0;
	r.top = 0;
	r.right  = width;
	r.bottom = height;

	AdjustWindowRect( &r, stylebits, FALSE );

	width = r.right - r.left;
	height = r.bottom - r.top;

	if( fullscreen )
	{
		x = 0;
		y = 0;
	}
	else if( parentHWND )
	{
		RECT parentWindowRect;

		GetWindowRect( parentHWND, &parentWindowRect );

		// share centre with the parent window
		x = (parentWindowRect.right - parentWindowRect.left - width) / 2;
		y = (parentWindowRect.bottom - parentWindowRect.top - height) / 2;
	}

	SetActiveWindow( glw_state.hWnd );

	SetWindowLong( glw_state.hWnd, GWL_EXSTYLE, exstyle );
	SetWindowLong( glw_state.hWnd, GWL_STYLE, stylebits );

	SetWindowPos( glw_state.hWnd, HWND_TOP, x, y, width, height, SWP_FRAMECHANGED );

	ShowWindow( glw_state.hWnd, SW_SHOW );
	UpdateWindow( glw_state.hWnd );

	SetForegroundWindow( glw_state.hWnd );
	SetFocus( glw_state.hWnd );
}
コード例 #12
0
bool DX11Application::Initialize()
{
    WNDCLASSEXW wc;

    ZeroMemory(&wc, sizeof(WNDCLASSEX));

    wc.cbSize = sizeof(WNDCLASSEX);
    wc.style = CS_HREDRAW | CS_VREDRAW;
    wc.lpfnWndProc = WindowProc;
    wc.hInstance = mInstanceHandle;
    wc.hCursor = LoadCursor(NULL, IDC_ARROW);
    wc.hbrBackground = (HBRUSH)COLOR_WINDOW;
    wc.lpszClassName = L"WindowClass";

    RegisterClassExW(&wc);
    int argc = 0;

    RECT wr = {0, 0, mScreenWidth, mScreenHeight};
    AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE);

    mWindowHandle = CreateWindowExW(NULL,
                          L"WindowClass",
                          L"DX11 Template",
                          WS_OVERLAPPEDWINDOW,
                          0,
                          0,
                          wr.right - wr.left,
                          wr.bottom - wr.top,
                          NULL,
                          NULL,
                          mInstanceHandle,
                          NULL);

    ShowWindow(mWindowHandle, SW_SHOW);

    DXGI_SWAP_CHAIN_DESC scd;

    ZeroMemory(&scd, sizeof(DXGI_SWAP_CHAIN_DESC));

    scd.BufferCount					= 1;
    scd.BufferDesc.Format			= DXGI_FORMAT_R8G8B8A8_UNORM;
    scd.BufferDesc.Width			= mScreenWidth;
    scd.BufferDesc.Height			= mScreenHeight;
    scd.BufferUsage					= DXGI_USAGE_RENDER_TARGET_OUTPUT;
    scd.OutputWindow				= mWindowHandle;
    scd.SampleDesc.Count			= 1;
    scd.SampleDesc.Quality			= 0;
    scd.Windowed					= TRUE;
    scd.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
    scd.BufferDesc.Scaling			= DXGI_MODE_SCALING_UNSPECIFIED;
    scd.SwapEffect					= DXGI_SWAP_EFFECT_DISCARD;
    scd.Flags						= DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;

    D3D_FEATURE_LEVEL featureLevels[] = {D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0};
    D3D11CreateDeviceAndSwapChain(NULL,
                                  D3D_DRIVER_TYPE_HARDWARE,
                                  NULL,
                                  NULL,
                                  featureLevels,
                                  3,
                                  D3D11_SDK_VERSION,
                                  &scd,
                                  &mSwapChain,
                                  &mDevice,
                                  NULL,
                                  &mDeviceContext);

    ID3D11Texture2D *BackBuffer;
    mSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&BackBuffer);
    mDevice->CreateRenderTargetView(BackBuffer, NULL, &mBackBuffer);
    BackBuffer->Release();


    // Create the depth/stencil buffer and view.
    D3D11_TEXTURE2D_DESC depthBufferDesc;
    ZeroMemory(&depthBufferDesc, sizeof(depthBufferDesc));
    depthBufferDesc.Width     = mScreenWidth;
    depthBufferDesc.Height    = mScreenHeight;
    depthBufferDesc.MipLevels = 1;
    depthBufferDesc.ArraySize = 1;
    depthBufferDesc.Format    = DXGI_FORMAT_D24_UNORM_S8_UINT;
    depthBufferDesc.SampleDesc.Count   = 1; // multisampling must match
    depthBufferDesc.SampleDesc.Quality = 0; // swap chain values.
    depthBufferDesc.Usage          = D3D11_USAGE_DEFAULT;
    depthBufferDesc.BindFlags      = D3D11_BIND_DEPTH_STENCIL;
    depthBufferDesc.CPUAccessFlags = 0; 
    depthBufferDesc.MiscFlags      = 0;

    int result = mDevice->CreateTexture2D(&depthBufferDesc, 0, &mDepthStencilBuffer);
    if(FAILED(result))
    {
        return false;
    }

    D3D11_DEPTH_STENCIL_DESC depthStencilDesc;
    ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc));

    // Set up the description of the stencil state.
    depthStencilDesc.DepthEnable = true;
    depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
    depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;

    depthStencilDesc.StencilEnable = true;
    depthStencilDesc.StencilReadMask = 0xFF;
    depthStencilDesc.StencilWriteMask = 0xFF;

    // Stencil operations if pixel is front-facing.
    depthStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
    depthStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
    depthStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
    depthStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

    // Stencil operations if pixel is back-facing.
    depthStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
    depthStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
    depthStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
    depthStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;


    result = mDevice->CreateDepthStencilState(&depthStencilDesc, &mDepthStencilState);
    if(FAILED(result))
    {
        return false;
    }
    mDeviceContext->OMSetDepthStencilState(mDepthStencilState, 1);
    //mDeviceContext->OMSetDepthStencilState(0, 0);
    D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc;
    ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc));

    // Set up the depth stencil view description.
    depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
    depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
    depthStencilViewDesc.Texture2D.MipSlice = 0;

    result = mDevice->CreateDepthStencilView(mDepthStencilBuffer, &depthStencilViewDesc, &mDepthStencilView);
    if(FAILED(result))
    {
        return false;
    }

    mDeviceContext->OMSetRenderTargets(1, &mBackBuffer, mDepthStencilView);

    // Setup the raster description which will determine how and what polygons will be drawn.
    D3D11_RASTERIZER_DESC rasterDesc;
    rasterDesc.AntialiasedLineEnable = false;
    rasterDesc.CullMode = D3D11_CULL_BACK;
    rasterDesc.DepthBias = 0;
    rasterDesc.DepthBiasClamp = 0.0f;
    rasterDesc.DepthClipEnable = true;
    rasterDesc.FillMode = D3D11_FILL_SOLID;
    rasterDesc.FrontCounterClockwise = false;
    rasterDesc.MultisampleEnable = false;
    rasterDesc.ScissorEnable = false;
    rasterDesc.SlopeScaledDepthBias = 0.0f;

    // Create the rasterizer state from the description we just filled out.
    result = mDevice->CreateRasterizerState(&rasterDesc, &mRasterState);
    if(FAILED(result))
    {
        return false;
    }

    // Now set the rasterizer state.
    mDeviceContext->RSSetState(mRasterState);



    D3D11_VIEWPORT viewport;
    ZeroMemory(&viewport, sizeof(D3D11_VIEWPORT));

    viewport.TopLeftX = 0;
    viewport.TopLeftY = 0;
    viewport.Width = (float)mScreenWidth;
    viewport.Height = (float)mScreenHeight;
    viewport.MinDepth = 0.0f;
    viewport.MaxDepth = 1.0f;

    mDeviceContext->RSSetViewports(1, &viewport);

    mTimer.Reset();

    return true;
}
コード例 #13
0
ファイル: punity.c プロジェクト: gingerBill/LD35
int CALLBACK
WinMain(HINSTANCE instance, HINSTANCE prev_instance, LPSTR command_line, int show_code)
{
    static Bank s_stack = {0};
    static Bank s_storage = {0};
    static Core s_core = {0};
    static Bitmap s_canvas = {0};
    WNDCLASSA window_class = {0};
    u32 *window_buffer = NULL;
    BITMAPINFO window_bmi = {0};


    if (align_to(CANVAS_WIDTH, 16) != CANVAS_WIDTH) {
        printf("CANVAS_WIDTH must be aligned to 16.\n");
        return 1;
    }


    CORE = &s_core;
    CORE->running = 1;
    CORE->stack = &s_stack;
    CORE->storage = &s_storage;

    bank_init(CORE->stack, STACK_CAPACITY);
    bank_init(CORE->storage, STORAGE_CAPACITY);

    // TODO: Push canvas to storage? Storage is not initialized yet, so we cannot push it there.
    CORE->canvas = &s_canvas;
    bitmap_init(CORE->canvas, CANVAS_WIDTH, CANVAS_HEIGHT, 0, 0);
    bitmap_clear(CORE->canvas, COLOR_TRANSPARENT);

    clip_reset();

    CORE->audio_volume = PUNP_SOUND_DEFAULT_MASTER_VOLUME;

    //
    //
    //

    punp_win32_instance = instance;
    QueryPerformanceFrequency((LARGE_INTEGER *)&punp_win32_perf_counter_frequency);

    // b32 sleep_is_granular = (timeBeginPeriod(1 /*ms*/) == TIMERR_NOERROR);

#ifndef RELEASE_BUILD
    printf("Debug build...");
    if (AttachConsole(ATTACH_PARENT_PROCESS) || AllocConsole()) {
        freopen("CONOUT$", "w", stdout);
        freopen("CONOUT$", "w", stderr);
    }
#else
    printf("Release build...");
#endif

    window_class.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
    window_class.lpfnWndProc = win32_window_callback;
    window_class.hInstance = punp_win32_instance;
    // window_class.hIcon = (HICON)LoadImage(0, "icon.ico", IMAGE_ICON, 0, 0, LR_LOADFROMFILE | LR_DEFAULTSIZE | LR_SHARED);
    window_class.hIcon = (HICON)LoadIcon(instance, "icon.ico");
    window_class.hCursor = LoadCursor(0, IDC_ARROW);
    window_class.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
    window_class.lpszClassName = "Punity";

    if (!RegisterClassA(&window_class)) {
        printf("RegisterClassA failed.\n");
        return 1;
    }

    {
        int screen_width = GetSystemMetrics(SM_CXSCREEN);
        int screen_height = GetSystemMetrics(SM_CYSCREEN);
        RECT rc;
        DWORD style = WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX;

        rc.left = (screen_width - (PUNP_WINDOW_WIDTH)) / 2;
        rc.top = (screen_height - (PUNP_WINDOW_HEIGHT)) / 2;
        rc.right = rc.left + PUNP_WINDOW_WIDTH;
        rc.bottom = rc.top + PUNP_WINDOW_HEIGHT;


        ASSERT(AdjustWindowRect(&rc, style, FALSE) != 0);

        // int window_width  = rc.right - rc.left;
        // int window_height = rc.bottom - rc.top;
        // rc.left = (screen_width  - width) / 2;
        // rc.top  = (screen_height - height) / 2;

        punp_win32_window = CreateWindowExA(
                0,
                window_class.lpszClassName,
                WINDOW_TITLE,
                style,
                rc.left, rc.top,
                rc.right - rc.left, rc.bottom - rc.top,
                0, 0,
                punp_win32_instance,
                0);
    }
    if (!punp_win32_window) {
        printf("CreateWindowExA failed.\n");
        return 1;
    }

    // Canvas
    window_bmi.bmiHeader.biSize = sizeof(window_bmi.bmiHeader);
    window_bmi.bmiHeader.biWidth = CANVAS_WIDTH;
    window_bmi.bmiHeader.biHeight = CANVAS_HEIGHT;
    window_bmi.bmiHeader.biPlanes = 1;
    window_bmi.bmiHeader.biBitCount = 32;
    window_bmi.bmiHeader.biCompression = BI_RGB;

    window_buffer = (u32 *)bank_push(CORE->stack, (CANVAS_WIDTH * 4) * CANVAS_HEIGHT);
    ASSERT(window_buffer);

    // Sound

    if (punp_win32_sound_init() == 0) {
        punp_win32_audio_buffer = 0;
    }


    init();


    // TODO: Center window
    ShowWindow(punp_win32_window, SW_SHOW);

    {
        f64 frame_time_stamp, frame_time_now, frame_time_delta;
        int x, y;
        u32 *window_row;
        u8 *canvas_it;
        MSG message;
        perf_from(&CORE->perf_frame);
        while (CORE->running) {
            perf_to(&CORE->perf_frame);
            perf_from(&CORE->perf_frame_inner);

            memset(&CORE->key_deltas, 0, KEYS_MAX);

            while (PeekMessage(&message, 0, 0, 0, PM_REMOVE)) {
                if (message.message == WM_QUIT) {
                    CORE->running = 0;
                }

                TranslateMessage(&message);
                DispatchMessageA(&message);
            }

            perf_from(&CORE->perf_step);
            step();
            perf_to(&CORE->perf_step);

            perf_from(&CORE->perf_audio);
            if (punp_win32_audio_buffer) {
                punp_win32_sound_step();
            }
            perf_to(&CORE->perf_audio);

            perf_from(&CORE->perf_blit);
            perf_from(&CORE->perf_blit_cvt);
            canvas_it = CORE->canvas->pixels;
            for (y = CANVAS_HEIGHT; y != 0; --y) {
                window_row = window_buffer + ((y - 1) * CANVAS_WIDTH);
                for (x = 0; x != CANVAS_WIDTH; ++x) {
                    *(window_row++) = CORE->palette.colors[*canvas_it++].rgba;
                }
            }
            perf_to(&CORE->perf_blit_cvt);

            perf_from(&CORE->perf_blit_gdi);
            {
                HDC dc = GetDC(punp_win32_window);
        #if 1
                // TODO: This is sadly slow (50us on my machine), need to find a faster way to do this.
                StretchDIBits(dc,
                              0, 0, CANVAS_WIDTH * CANVAS_SCALE, CANVAS_HEIGHT * CANVAS_SCALE,
                              0, 0, CANVAS_WIDTH, CANVAS_HEIGHT,
                              window_buffer,
                              &window_bmi,
                              DIB_RGB_COLORS,
                              SRCCOPY);
        #else
        #endif
                ReleaseDC(punp_win32_window, dc);
            }
            perf_to(&CORE->perf_blit_gdi);
            perf_to(&CORE->perf_blit);

            perf_to(&CORE->perf_frame_inner);

            {
                f32 frame_delta = perf_delta(&CORE->perf_frame);
                if (frame_delta < PUNP_FRAME_TIME) {
                    // printf("sleeping ... %.3f\n", (f32)PUNP_FRAME_TIME - frame_delta);
                    Sleep((PUNP_FRAME_TIME - frame_delta) * 1e3);
                }
            }
            CORE->frame++;

    #if 0
            printf("stack %d storage %d\n",
                   CORE->stack->it - CORE->stack->begin,
                   CORE->storage->it - CORE->storage->begin);
    #endif
        }
    }

#if PUNP_SOUND_DEBUG_FILE
    fclose(punp_audio_buf_file);
#endif

    return 0;
}
コード例 #14
0
ファイル: GameProcedure.cpp プロジェクト: gitrider/wxsj2
VOID CGameProcedure::CreateMainWnd(VOID)
{
	INT nWinWidth  = 0;
	INT nWinHeight = 0;

	if( s_pVariableSystem )
	{
		BOOL bHave = FALSE;
		fVector2 fResoution = CVariableSystem::GetMe()->GetAs_Vector2( "View_Resoution" , &bHave);

		if (bHave)
		{
			nWinWidth  = (INT)fResoution.x;
			nWinHeight = (INT)fResoution.y;
		}
		else
		{
			nWinWidth  = DEFWINDOW_WIDTH;
			nWinHeight = DEFWINDOW_HEIGHT;
		}
	}
	else
	{
		nWinWidth  = DEFWINDOW_WIDTH;
		nWinHeight = DEFWINDOW_HEIGHT;
	}


	// 计算窗口大小
	m_bMinimized		= FALSE;
	m_bFullScreen		= TRUE;

	SetRect( &m_rectWindow, 0, 0, nWinWidth, nWinHeight );
	AdjustWindowRect( &m_rectWindow, DEFWINDOW_STYLE, FALSE );

	SetRect( &m_rectFCOffset, 
			 m_rectWindow.left, 
			 m_rectWindow.top, 
			 m_rectWindow.right  - nWinWidth, 
			 m_rectWindow.bottom - nWinHeight
			);

	UINT dwX = (::GetSystemMetrics(SM_CXFULLSCREEN)-(m_rectWindow.right-m_rectWindow.left))/2;
	UINT dwY = (::GetSystemMetrics(SM_CYFULLSCREEN)-(m_rectWindow.bottom-m_rectWindow.top))/2;
	OffsetRect(&m_rectWindow, -m_rectFCOffset.left, -m_rectFCOffset.top);
	OffsetRect(&m_rectWindow, dwX, dwY);

	m_bActive			= true;
	m_bRenderingPaused	= FALSE;

	// 注册窗口类
	WNDCLASSEX wcex;

	wcex.cbSize = sizeof(WNDCLASSEX); 

	wcex.style			= CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
	wcex.lpfnWndProc	= (WNDPROC)_MainWndProc;
	wcex.cbClsExtra		= 0;
	wcex.cbWndExtra		= 0;
	wcex.hInstance		= g_hInstance;
	wcex.hIcon			= LoadIcon(g_hInstance, (LPCTSTR)IDD_GAME_DIALOG);
	wcex.hCursor		= LoadCursor( NULL, IDC_ARROW );
	wcex.hbrBackground	= (HBRUSH)NULL; //GetStockObject(WHITE_BRUSH);
	wcex.lpszMenuName	= (LPCTSTR)NULL;
	wcex.lpszClassName	= MAINWINDOW_CLASS;
	wcex.hIconSm		= LoadIcon(wcex.hInstance, (LPCTSTR)IDI_SMALL);

	RegisterClassEx(&wcex);

	// 创建窗口
	CHAR szTitle[MAX_PATH];
	_snprintf(szTitle, MAX_PATH, "%s %s (%s %s)", GAME_TITLE, VERSION_INFO, __DATE__, __TIME__);

	HWND hWnd = CreateWindowEx(	NULL, MAINWINDOW_CLASS, szTitle, 
								DEFWINDOW_STYLE,
								m_rectWindow.left, m_rectWindow.top, 
								m_rectWindow.right-m_rectWindow.left, 
								m_rectWindow.bottom-m_rectWindow.top,
								NULL, NULL, g_hInstance, NULL);

	if(!hWnd)
	{
		KLThrow(_T("Can't create main window!"));
	}

	ShowWindow(hWnd, SW_SHOW);
	UpdateWindow(hWnd);

	g_hMainWnd = hWnd;
}
コード例 #15
0
/*
 * Resize the current window so that it fits the whole screen
 */
void FGAPIENTRY glutFullScreen( void )
{
    FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutFullScreen" );
    FREEGLUT_EXIT_IF_NO_WINDOW ( "glutFullScreen" );

    {
#if TARGET_HOST_UNIX_X11
        int x, y;
        Window w;

        XMoveResizeWindow(
            fgDisplay.Display,
            fgStructure.CurrentWindow->Window.Handle,
            0, 0,
            fgDisplay.ScreenWidth,
            fgDisplay.ScreenHeight
        );

        XFlush( fgDisplay.Display ); /* This is needed */

        XTranslateCoordinates(
            fgDisplay.Display,
            fgStructure.CurrentWindow->Window.Handle,
            fgDisplay.RootWindow,
            0, 0, &x, &y, &w
        );

        if (x || y)
        {
            XMoveWindow(
                fgDisplay.Display,
                fgStructure.CurrentWindow->Window.Handle,
                -x, -y
            );
            XFlush( fgDisplay.Display ); /* XXX Shouldn't need this */
        }
#elif TARGET_HOST_WIN32
        RECT rect;

        /* For fullscreen mode, force the top-left corner to 0,0
         * and adjust the window rectangle so that the client area
         * covers the whole screen.
         */

        rect.left   = 0;
        rect.top    = 0;
        rect.right  = fgDisplay.ScreenWidth;
        rect.bottom = fgDisplay.ScreenHeight;

        AdjustWindowRect ( &rect, WS_OVERLAPPEDWINDOW | WS_CLIPSIBLINGS |
                                  WS_CLIPCHILDREN, FALSE );

        /*
         * SWP_NOACTIVATE     Do not activate the window
         * SWP_NOOWNERZORDER  Do not change position in z-order
         * SWP_NOSENDCHANGING Supress WM_WINDOWPOSCHANGING message
         * SWP_NOZORDER       Retains the current Z order (ignore 2nd param)
         */

        SetWindowPos( fgStructure.CurrentWindow->Window.Handle,
                      HWND_TOP,
                      rect.left,
                      rect.top,
                      rect.right  - rect.left,
                      rect.bottom - rect.top,
                      SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOSENDCHANGING |
                      SWP_NOZORDER
                    );
#endif
    }
}
コード例 #16
0
ファイル: HW.cpp プロジェクト: BeaconDev/xray-16
void	CHW::updateWindowProps	(HWND m_hWnd)
{
//	BOOL	bWindowed				= strstr(Core.Params,"-dedicated") ? TRUE : !psDeviceFlags.is	(rsFullscreen);
//#ifndef DEDICATED_SERVER
//	BOOL	bWindowed				= !psDeviceFlags.is	(rsFullscreen);
//#else
//	BOOL	bWindowed				= TRUE;
//#endif

	BOOL	bWindowed				= TRUE;
#ifndef _EDITOR
	if (!g_dedicated_server)
		bWindowed			= !psDeviceFlags.is(rsFullscreen);
#endif	

	u32		dwWindowStyle			= 0;
	// Set window properties depending on what mode were in.
	if (bWindowed)		{
		if (m_move_window) {
			if (strstr(Core.Params,"-no_dialog_header"))
				SetWindowLong	( m_hWnd, GWL_STYLE, dwWindowStyle=(WS_BORDER|WS_VISIBLE) );
			else
				SetWindowLong	( m_hWnd, GWL_STYLE, dwWindowStyle=(WS_BORDER|WS_DLGFRAME|WS_VISIBLE|WS_SYSMENU|WS_MINIMIZEBOX ) );
			// When moving from fullscreen to windowed mode, it is important to
			// adjust the window size after recreating the device rather than
			// beforehand to ensure that you get the window size you want.  For
			// example, when switching from 640x480 fullscreen to windowed with
			// a 1000x600 window on a 1024x768 desktop, it is impossible to set
			// the window size to 1000x600 until after the display mode has
			// changed to 1024x768, because windows cannot be larger than the
			// desktop.

			RECT			m_rcWindowBounds;
			BOOL			bCenter = FALSE;
			if (strstr(Core.Params, "-center_screen"))	bCenter = TRUE;

#ifndef _EDITOR
			if (g_dedicated_server)
				bCenter		= TRUE;
#endif

			if(bCenter){
				RECT				DesktopRect;
				
				GetClientRect		(GetDesktopWindow(), &DesktopRect);

				SetRect(			&m_rcWindowBounds, 
									(DesktopRect.right-DevPP.BackBufferWidth)/2, 
									(DesktopRect.bottom-DevPP.BackBufferHeight)/2, 
									(DesktopRect.right+DevPP.BackBufferWidth)/2, 
									(DesktopRect.bottom+DevPP.BackBufferHeight)/2			);
			}else{
				SetRect(			&m_rcWindowBounds,
									0, 
									0, 
									DevPP.BackBufferWidth, 
									DevPP.BackBufferHeight );
			};

			AdjustWindowRect		(	&m_rcWindowBounds, dwWindowStyle, FALSE );

			SetWindowPos			(	m_hWnd, 
										HWND_NOTOPMOST,	
										m_rcWindowBounds.left, 
										m_rcWindowBounds.top,
										( m_rcWindowBounds.right - m_rcWindowBounds.left ),
										( m_rcWindowBounds.bottom - m_rcWindowBounds.top ),
										SWP_SHOWWINDOW|SWP_NOCOPYBITS|SWP_DRAWFRAME );
		}
	}
	else
	{
		SetWindowLong			( m_hWnd, GWL_STYLE, dwWindowStyle=(WS_POPUP|WS_VISIBLE) );
		SetWindowLong			( m_hWnd, GWL_EXSTYLE, WS_EX_TOPMOST);
	}

#ifndef _EDITOR
	if (!g_dedicated_server)
	{
		ShowCursor	(FALSE);
		SetForegroundWindow( m_hWnd );
	}
#endif
}
コード例 #17
0
ファイル: wgl_ctx.c プロジェクト: Gruncher/RetroArch
static bool gfx_ctx_wgl_set_video_mode(void *data,
      unsigned width, unsigned height,
      bool fullscreen)
{
   DWORD style;
   MSG msg;
   RECT mon_rect;
   MONITORINFOEX current_mon;
   float refresh_mod;
   unsigned refresh;
   bool windowed_full;
   RECT rect   = {0};
   HMONITOR hm_to_use = NULL;
   driver_t *driver     = driver_get_ptr();
   settings_t *settings = config_get_ptr();

   monitor_info(&current_mon, &hm_to_use);

   mon_rect        = current_mon.rcMonitor;
   g_resize_width  = width;
   g_resize_height = height;

   /* Windows only reports the refresh rates for modelines as 
    * an integer, so video.refresh_rate needs to be rounded. Also, account 
    * for black frame insertion using video.refresh_rate set to half
    * of the display refresh rate. */
   refresh_mod = settings->video.black_frame_insertion ? 2.0f : 1.0f;
   refresh = round(settings->video.refresh_rate * refresh_mod);

   windowed_full   = settings->video.windowed_fullscreen;

   if (fullscreen)
   {
      if (windowed_full)
      {
         style = WS_EX_TOPMOST | WS_POPUP;
         g_resize_width  = width  = mon_rect.right - mon_rect.left;
         g_resize_height = height = mon_rect.bottom - mon_rect.top;
      }
      else
      {
         style = WS_POPUP | WS_VISIBLE;

         if (!set_fullscreen(width, height, refresh, current_mon.szDevice))
            goto error;

         /* Display settings might have changed, get new coordinates. */
         GetMonitorInfo(hm_to_use, (MONITORINFO*)&current_mon);
         mon_rect = current_mon.rcMonitor;
         g_restore_desktop = true;
      }
   }
   else
   {
      style = WS_OVERLAPPEDWINDOW | WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
      rect.right  = width;
      rect.bottom = height;
      AdjustWindowRect(&rect, style, FALSE);
      g_resize_width  = width  = rect.right - rect.left;
      g_resize_height = height = rect.bottom - rect.top;
   }

   g_hwnd = CreateWindowEx(0, "RetroArch", "RetroArch", style,
         fullscreen ? mon_rect.left : g_pos_x,
         fullscreen ? mon_rect.top  : g_pos_y,
         width, height,
         NULL, NULL, NULL, NULL);

   if (!g_hwnd)
      goto error;

   if (!fullscreen || windowed_full)
   {
      if (!fullscreen && settings->ui.menubar_enable)
      {
         RECT rc_temp = {0, 0, (LONG)height, 0x7FFF};
         SetMenu(g_hwnd, LoadMenu(GetModuleHandle(NULL),MAKEINTRESOURCE(IDR_MENU)));
         SendMessage(g_hwnd, WM_NCCALCSIZE, FALSE, (LPARAM)&rc_temp);
         g_resize_height = height += rc_temp.top + rect.top;
         SetWindowPos(g_hwnd, NULL, 0, 0, width, height, SWP_NOMOVE);
      }

      ShowWindow(g_hwnd, SW_RESTORE);
      UpdateWindow(g_hwnd);
      SetForegroundWindow(g_hwnd);
      SetFocus(g_hwnd);
   }

   win32_show_cursor(!fullscreen);

   /* Wait until GL context is created (or failed to do so ...) */
   while (!g_inited && !g_quit && GetMessage(&msg, g_hwnd, 0, 0))
   {
      TranslateMessage(&msg);
      DispatchMessage(&msg);
   }

   if (g_quit)
      goto error;

   p_swap_interval = (BOOL (APIENTRY *)(int))wglGetProcAddress("wglSwapIntervalEXT");

   gfx_ctx_wgl_swap_interval(data, g_interval);

   driver->display_type  = RARCH_DISPLAY_WIN32;
   driver->video_display = 0;
   driver->video_window  = (uintptr_t)g_hwnd;

   return true;

error:
   gfx_ctx_wgl_destroy(data);
   return false;
}
コード例 #18
0
ファイル: wgl_ctx.c プロジェクト: AampApps/RetroArch
static bool gfx_ctx_set_video_mode(void *data,
      unsigned width, unsigned height,
      bool fullscreen)
{
   DWORD style;
   RECT rect   = {0};

   HMONITOR hm_to_use = NULL;
   MONITORINFOEX current_mon;

   monitor_info(&current_mon, &hm_to_use);
   RECT mon_rect = current_mon.rcMonitor;

   g_resize_width  = width;
   g_resize_height = height;

   bool windowed_full = g_settings.video.windowed_fullscreen;
   if (fullscreen)
   {
      if (windowed_full)
      {
         style = WS_EX_TOPMOST | WS_POPUP;
         g_resize_width  = width  = mon_rect.right - mon_rect.left;
         g_resize_height = height = mon_rect.bottom - mon_rect.top;
      }
      else
      {
         style = WS_POPUP | WS_VISIBLE;

         if (!set_fullscreen(width, height, current_mon.szDevice))
            goto error;

         // display settings might have changed, get new coordinates
         GetMonitorInfo(hm_to_use, (MONITORINFO*)&current_mon);
         mon_rect = current_mon.rcMonitor;
         g_restore_desktop = true;
      }
   }
   else
   {
      style = WS_OVERLAPPEDWINDOW | WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
      rect.right  = width;
      rect.bottom = height;
      AdjustWindowRect(&rect, style, FALSE);
      width  = rect.right - rect.left;
      height = rect.bottom - rect.top;
   }

   g_hwnd = CreateWindowEx(0, "RetroArch", "RetroArch", style,
         fullscreen ? mon_rect.left : g_pos_x,
         fullscreen ? mon_rect.top  : g_pos_y,
         width, height,
         NULL, NULL, NULL, NULL);

   if (!g_hwnd)
      goto error;

   if (!fullscreen || windowed_full)
   {
      ShowWindow(g_hwnd, SW_RESTORE);
      UpdateWindow(g_hwnd);
      SetForegroundWindow(g_hwnd);
      SetFocus(g_hwnd);
   }

   show_cursor(!fullscreen);

   // Wait until GL context is created (or failed to do so ...)
   MSG msg;
   while (!g_inited && !g_quit && GetMessage(&msg, g_hwnd, 0, 0))
   {
      TranslateMessage(&msg);
      DispatchMessage(&msg);
   }

   if (g_quit)
      goto error;

   p_swap_interval = (BOOL (APIENTRY *)(int))wglGetProcAddress("wglSwapIntervalEXT");

   gfx_ctx_swap_interval(data, g_interval);

   driver.display_type  = RARCH_DISPLAY_WIN32;
   driver.video_display = 0;
   driver.video_window  = (uintptr_t)g_hwnd;

   return true;

error:
   gfx_ctx_destroy(data);
   return false;
}
コード例 #19
0
ファイル: events.c プロジェクト: 839687571/vlc-2.2.1.32-2013
/*****************************************************************************
 * Win32VoutCreateWindow: create a window for the video.
 *****************************************************************************
 * Before creating a direct draw surface, we need to create a window in which
 * the video will be displayed. This window will also allow us to capture the
 * events.
 *****************************************************************************/
static int Win32VoutCreateWindow( event_thread_t *p_event )
{
    vout_display_t *vd = p_event->vd;
    HINSTANCE  hInstance;
    HMENU      hMenu;
    RECT       rect_window;
    WNDCLASS   wc;                            /* window class components */
    TCHAR      vlc_path[MAX_PATH+1];
    int        i_style, i_stylex;

    msg_Dbg( vd, "Win32VoutCreateWindow" );

    /* Get this module's instance */
    hInstance = GetModuleHandle(NULL);

    #ifdef MODULE_NAME_IS_direct3d
    if( !p_event->use_desktop )
    #endif
    {
        /* If an external window was specified, we'll draw in it. */
        p_event->parent_window = vout_display_NewWindow(vd, &p_event->wnd_cfg );
        if( p_event->parent_window )
            p_event->hparent = p_event->parent_window->handle.hwnd;
        else
            p_event->hparent = NULL;
    }
    #ifdef MODULE_NAME_IS_direct3d
    else
    {
        vout_display_DeleteWindow(vd, NULL);
        p_event->parent_window = NULL;
        p_event->hparent = GetDesktopHandle(vd);
    }
    #endif
    p_event->cursor_arrow = LoadCursor(NULL, IDC_ARROW);
    p_event->cursor_empty = EmptyCursor(hInstance);

    /* Get the Icon from the main app */
    p_event->vlc_icon = NULL;
    if( GetModuleFileName( NULL, vlc_path, MAX_PATH ) )
    {
        p_event->vlc_icon = ExtractIcon( hInstance, vlc_path, 0 );
    }

    /* Fill in the window class structure */
    wc.style         = CS_OWNDC|CS_DBLCLKS;          /* style: dbl click */
    wc.lpfnWndProc   = (WNDPROC)WinVoutEventProc;       /* event handler */
    wc.cbClsExtra    = 0;                         /* no extra class data */
    wc.cbWndExtra    = 0;                        /* no extra window data */
    wc.hInstance     = hInstance;                            /* instance */
    wc.hIcon         = p_event->vlc_icon;       /* load the vlc big icon */
    wc.hCursor       = p_event->is_cursor_hidden ? p_event->cursor_empty :
                                                   p_event->cursor_arrow;
    wc.hbrBackground = GetStockObject(BLACK_BRUSH);  /* background color */
    wc.lpszMenuName  = NULL;                                  /* no menu */
    wc.lpszClassName = p_event->class_main;       /* use a special class */

    /* Register the window class */
    if( !RegisterClass(&wc) )
    {
        if( p_event->vlc_icon )
            DestroyIcon( p_event->vlc_icon );

        msg_Err( vd, "Win32VoutCreateWindow RegisterClass FAILED (err=%lu)", GetLastError() );
        return VLC_EGENERIC;
    }

    /* Register the video sub-window class */
    wc.lpszClassName = p_event->class_video;
    wc.hIcon = 0;
    wc.hbrBackground = NULL; /* no background color */
    if( !RegisterClass(&wc) )
    {
        msg_Err( vd, "Win32VoutCreateWindow RegisterClass FAILED (err=%lu)", GetLastError() );
        return VLC_EGENERIC;
    }

    /* When you create a window you give the dimensions you wish it to
     * have. Unfortunatly these dimensions will include the borders and
     * titlebar. We use the following function to find out the size of
     * the window corresponding to the useable surface we want */
    rect_window.left   = 10;
    rect_window.top    = 10;
    rect_window.right  = rect_window.left + p_event->wnd_cfg.width;
    rect_window.bottom = rect_window.top  + p_event->wnd_cfg.height;

    if( var_GetBool( vd, "video-deco" ) )
    {
        /* Open with window decoration */
        AdjustWindowRect( &rect_window, WS_OVERLAPPEDWINDOW|WS_SIZEBOX, 0 );
        i_style = WS_OVERLAPPEDWINDOW|WS_SIZEBOX|WS_VISIBLE|WS_CLIPCHILDREN;
        i_stylex = 0;
    }
    else
    {
        /* No window decoration */
        AdjustWindowRect( &rect_window, WS_POPUP, 0 );
        i_style = WS_POPUP|WS_VISIBLE|WS_CLIPCHILDREN;
        i_stylex = 0; // WS_EX_TOOLWINDOW; Is TOOLWINDOW really needed ?
                      // It messes up the fullscreen window.
    }

    if( p_event->hparent )
    {
        i_style = WS_VISIBLE|WS_CLIPCHILDREN|WS_CHILD;
        i_stylex = 0;

        /* allow user to regain control over input events if requested */
        bool b_mouse_support = var_InheritBool( vd, "mouse-events" );
        bool b_key_support = var_InheritBool( vd, "keyboard-events" );
        if( !b_mouse_support && !b_key_support )
            i_style |= WS_DISABLED;
    }

    p_event->i_window_style = i_style;

    /* Create the window */
    p_event->hwnd =
        CreateWindowEx( WS_EX_NOPARENTNOTIFY | i_stylex,
                    p_event->class_main,             /* name of window class */
                    _T(VOUT_TITLE) _T(" (VLC Video Output)"),  /* window title */
                    i_style,                                 /* window style */
                    (!p_event->wnd_cfg.x) ? (UINT)CW_USEDEFAULT :
                        (UINT)p_event->wnd_cfg.x,   /* default X coordinate */
                    (!p_event->wnd_cfg.y) ? (UINT)CW_USEDEFAULT :
                        (UINT)p_event->wnd_cfg.y,   /* default Y coordinate */
                    rect_window.right - rect_window.left,    /* window width */
                    rect_window.bottom - rect_window.top,   /* window height */
                    p_event->hparent,                       /* parent window */
                    NULL,                          /* no menu in this window */
                    hInstance,            /* handle of this program instance */
                    (LPVOID)p_event );           /* send vd to WM_CREATE */

    if( !p_event->hwnd )
    {
        msg_Warn( vd, "Win32VoutCreateWindow create window FAILED (err=%lu)", GetLastError() );
        return VLC_EGENERIC;
    }

    InitGestures( p_event->hwnd, &p_event->p_gesture );

    if( p_event->hparent )
    {
        LONG i_style;

        /* We don't want the window owner to overwrite our client area */
        i_style = GetWindowLong( p_event->hparent, GWL_STYLE );

        if( !(i_style & WS_CLIPCHILDREN) )
            /* Hmmm, apparently this is a blocking call... */
            SetWindowLong( p_event->hparent, GWL_STYLE,
                           i_style | WS_CLIPCHILDREN );

        /* Create our fullscreen window */
        p_event->hfswnd =
            CreateWindowEx( WS_EX_APPWINDOW, p_event->class_main,
                            _T(VOUT_TITLE) _T(" (VLC Fullscreen Video Output)"),
                            WS_OVERLAPPEDWINDOW|WS_CLIPCHILDREN|WS_SIZEBOX,
                            CW_USEDEFAULT, CW_USEDEFAULT,
                            CW_USEDEFAULT, CW_USEDEFAULT,
                            NULL, NULL, hInstance, NULL );
    }
    else
    {
        p_event->hfswnd = NULL;
    }

    /* Append a "Always On Top" entry in the system menu */
    hMenu = GetSystemMenu( p_event->hwnd, FALSE );
    AppendMenu( hMenu, MF_SEPARATOR, 0, _T("") );
    AppendMenu( hMenu, MF_STRING | MF_UNCHECKED,
                       IDM_TOGGLE_ON_TOP, _T("Always on &Top") );

    /* Create video sub-window. This sub window will always exactly match
     * the size of the video, which allows us to use crazy overlay colorkeys
     * without having them shown outside of the video area. */
    /* FIXME vd->source.i_width/i_height seems wrong */
    p_event->hvideownd =
    CreateWindow( p_event->class_video, _T(""),   /* window class */
        WS_CHILD,                   /* window style, not visible initially */
        0, 0,
        vd->source.i_width,          /* default width */
        vd->source.i_height,        /* default height */
        p_event->hwnd,               /* parent window */
        NULL, hInstance,
        (LPVOID)p_event );    /* send vd to WM_CREATE */

    if( !p_event->hvideownd )
        msg_Warn( vd, "can't create video sub-window" );
    else
        msg_Dbg( vd, "created video sub-window" );

    /* Now display the window */
    ShowWindow( p_event->hwnd, SW_SHOW );

    return VLC_SUCCESS;
}
コード例 #20
0
ファイル: glw_imp.c プロジェクト: Izhido/qrevpak
qboolean VID_CreateWindow( int width, int height, qboolean fullscreen )
{
	WNDCLASS		wc;
	RECT			r;
	cvar_t			*vid_xpos, *vid_ypos;
	int				stylebits;
	int				x, y, w, h;
	int				exstyle;

	/* Register the frame class */
    wc.style         = 0;
    wc.lpfnWndProc   = (WNDPROC)glw_state.wndproc;
    wc.cbClsExtra    = 0;
    wc.cbWndExtra    = 0;
    wc.hInstance     = glw_state.hInstance;
    wc.hIcon         = 0;
    wc.hCursor       = LoadCursor (NULL,IDC_ARROW);
	wc.hbrBackground = (void *)COLOR_GRAYTEXT;
    wc.lpszMenuName  = 0;
    wc.lpszClassName = WINDOW_CLASS_NAME;

    if (!RegisterClass (&wc) )
		ri.Sys_Error (ERR_FATAL, "Couldn't register window class");

	if (fullscreen)
	{
		exstyle = WS_EX_TOPMOST;
		stylebits = WS_POPUP|WS_VISIBLE;
	}
	else
	{
		exstyle = 0;
		stylebits = WINDOW_STYLE;
	}

	r.left = 0;
	r.top = 0;
	r.right  = width;
	r.bottom = height;

	AdjustWindowRect (&r, stylebits, FALSE);

	w = r.right - r.left;
	h = r.bottom - r.top;

	if (fullscreen)
	{
		x = 0;
		y = 0;
	}
	else
	{
		vid_xpos = ri.Cvar_Get ("vid_xpos", "0", 0);
		vid_ypos = ri.Cvar_Get ("vid_ypos", "0", 0);
		x = vid_xpos->value;
		y = vid_ypos->value;
	}

	glw_state.hWnd = CreateWindowEx (
		 exstyle, 
		 WINDOW_CLASS_NAME,
		 "Quake 2",
		 stylebits,
		 x, y, w, h,
		 NULL,
		 NULL,
		 glw_state.hInstance,
		 NULL);

	if (!glw_state.hWnd)
		ri.Sys_Error (ERR_FATAL, "Couldn't create window");
	
	ShowWindow( glw_state.hWnd, SW_SHOW );
	UpdateWindow( glw_state.hWnd );

	// init all the gl stuff for the window
	if (!GLimp_InitGL ())
	{
		ri.Con_Printf( PRINT_ALL, "VID_CreateWindow() - GLimp_InitGL failed\n");
		return false;
	}

	SetForegroundWindow( glw_state.hWnd );
	SetFocus( glw_state.hWnd );

	// let the sound and input subsystems know about the new window
	ri.Vid_NewWindow (width, height);

	return true;
}
コード例 #21
0
ファイル: main.cpp プロジェクト: alex-ks/verdant
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 = L"DX11BookWindowClass";
	wndClass.hIcon = ExtractIcon( hInstance, L"icon.ico", 0 );

    if( !RegisterClassEx( &wndClass ) )
        return -1;

    RECT rc = { 0, 0, 800, 600 };
    AdjustWindowRect( &rc, WS_OVERLAPPEDWINDOW, FALSE );

    HWND hwnd = CreateWindow( L"DX11BookWindowClass", L"Not Blank Win32 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 );

	//DXBase *demo = new SpriteDemo( );
	DXEngine demo;

	bool result = demo.initialize( hInstance, hwnd );
	if ( result == false )
		return -1;

	VisualEntity ar[2];

	wstring path1 = L"decal.dds";
	wstring path2 = L"wheel.dds";

	ar[0].bindTexture( path1 );
	ar[1].bindTexture( path2 );
	
	ar[0].setPosition( XMFLOAT2( 200.0f, 500.0f ) );
	ar[1].setPosition( XMFLOAT2( 400.0f, 200.0f ) );

	ar[0].setDepth( 0.5f );
	ar[1].setDepth( 0.5f );

	ar[0].setSize( XMFLOAT2( 500.0f, 500.0f ) );
	ar[1].setSize( XMFLOAT2( 100.0f, 100.0f ) );

	float px = 400;
	float py = 200;
	float deltaX = 0.2f;
	float deltaY = 0.2f;

	demo.loadEntities( ar, 2 );

    MSG msg = { 0 };

	bool firstUse = true;

    while( msg.message != WM_QUIT )
    {
        if( PeekMessage( &msg, 0, 0, 0, PM_REMOVE ) )
        {
            TranslateMessage( &msg );
            DispatchMessage( &msg );
        }
        else
        {
            // Update
            // Draw
			demo.update( 0.0f );
			demo.render( );
			ar[1].setPosition( XMFLOAT2(px += deltaX, py += deltaY) );
			//deltaX += deltaX * 0.0005f;
			//deltaY += deltaY * 0.0005f;
			if ( px >= 700 || px <= 0 ) 
				deltaX *= -1;
			if ( py >= 600 || py <= 100 )
				deltaY *= -1;
        }
	}
    // Demo Shutdown
	// demo->shutdown( ); WHY?
    return static_cast<int>( msg.wParam );
}
コード例 #22
0
static DWORD WINAPI gr_open_graph_internal(value arg)
{
  RECT rc;
  int ret;
  int event;
  int x, y, w, h;
  int screenx,screeny;
  int attributes;
  static int registered;
  MSG msg;

  gr_initialized = TRUE;
  hInst = GetModuleHandle(NULL);
  x = y = w = h = CW_USEDEFAULT;
  sscanf(String_val(arg), "%dx%d+%d+%d", &w, &h, &x, &y);

  /* Open the display */
  if (grwindow.hwnd == NULL || !IsWindow(grwindow.hwnd)) {
    if (!registered) {
      registered = DoRegisterClass();
      if (!registered) {
        open_graph_errmsg = "Cannot register the window class";
        SetEvent(open_graph_event);
        return 1;
      }
    }
    grwindow.hwnd = CreateWindow(szOcamlWindowClass,
                                 WINDOW_NAME,
                                 WS_OVERLAPPEDWINDOW,
                                 x,y,
                                 w,h,
                                 NULL,0,hInst,NULL);
    if (grwindow.hwnd == NULL) {
      open_graph_errmsg = "Cannot create window";
      SetEvent(open_graph_event);
      return 1;
    }
#if 0
    if (x != CW_USEDEFAULT) {
      rc.left = 0;
      rc.top = 0;
      rc.right = w;
      rc.bottom = h;
      AdjustWindowRect(&rc,GetWindowLong(grwindow.hwnd,GWL_STYLE),0);
      MoveWindow(grwindow.hwnd,x,y,rc.right-rc.left,rc.bottom-rc.top,1);
    }
#endif
  }
  gr_reset();
  ShowWindow(grwindow.hwnd,SW_SHOWNORMAL);
  
  /* Position the current point at origin */
  grwindow.grx = 0;
  grwindow.gry = 0;
  
  caml_gr_init_event_queue();

  /* The global data structures are now correctly initialized.
     Restart the Caml main thread. */
  open_graph_errmsg = NULL;
  SetEvent(open_graph_event);

  /* Enter the message handling loop */
  while (GetMessage(&msg,NULL,0,0)) {
    TranslateMessage(&msg);  // Translates virtual key codes
    DispatchMessage(&msg);   // Dispatches message to window
    if (!IsWindow(grwindow.hwnd))
      break;
  }
  return 0;
}
コード例 #23
0
ファイル: Win32Window.cpp プロジェクト: lighttransport/nanort
void	Win32Window::createWindow(const b3gWindowConstructionInfo& ci)
{
	int oglViewportWidth = ci.m_width;
	int oglViewportHeight = ci.m_height;
	bool fullscreen = ci.m_fullscreen;
	int colorBitsPerPixel = ci.m_colorBitsPerPixel;
	void* windowHandle = ci.m_windowHandle;

	// get handle to exe file
	HINSTANCE hInstance = GetModuleHandle(0);


	// create the window if we need to and we do not use the null device
	if (!windowHandle)
	{
#ifdef UNICODE
		const wchar_t * ClassName = L"DeviceWin32";
		const wchar_t*  emptyString= L"";
#else
		const char* ClassName = "DeviceWin32";
		const char* emptyString = "";
#endif
		// Register Class
		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( NULL, IDI_APPLICATION ); //(HICON)LoadImage(hInstance, "bullet_ico.ico", IMAGE_ICON, 0,0, LR_LOADTRANSPARENT);//LR_LOADFROMFILE);
		wcex.hCursor		= LoadCursor(NULL, IDC_ARROW);
		wcex.hbrBackground	= (HBRUSH)(COLOR_WINDOW+1);
		wcex.lpszMenuName	= 0;
		wcex.lpszClassName	= ClassName;
		wcex.hIconSm		= 0;

		// if there is an icon, load it
//		wcex.hIcon = (HICON)LoadImage(hInstance, "bullet.ico", IMAGE_ICON, 0,0, LR_LOADFROMFILE);

		RegisterClassEx(&wcex);

		// calculate client size

		RECT clientSize;
		clientSize.top = 0;
		clientSize.left = 0;
		clientSize.right = oglViewportWidth;
		clientSize.bottom = oglViewportHeight;

		DWORD style = WS_POPUP;

		if (!fullscreen)
			style = WS_SYSMENU | WS_BORDER | WS_CAPTION | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_SIZEBOX;

		AdjustWindowRect(&clientSize, style, false);
		
		m_data->m_fullWindowWidth = clientSize.right - clientSize.left;
		m_data->m_fullWindowHeight = clientSize.bottom - clientSize.top;

		int windowLeft = (GetSystemMetrics(SM_CXSCREEN) - m_data->m_fullWindowWidth) / 2;
		int windowTop = (GetSystemMetrics(SM_CYSCREEN) - m_data->m_fullWindowHeight) / 2;

		if (fullscreen)
		{
			windowLeft = 0;
			windowTop = 0;
		}

		// create window

		m_data->m_hWnd = CreateWindow( ClassName, emptyString, style, windowLeft, windowTop,
			m_data->m_fullWindowWidth, m_data->m_fullWindowHeight,NULL, NULL, hInstance, NULL);

		
		RECT clientRect;
		GetClientRect(m_data->m_hWnd,&clientRect);



		ShowWindow(m_data->m_hWnd, SW_SHOW);
		UpdateWindow(m_data->m_hWnd);

		MoveWindow(m_data->m_hWnd, windowLeft, windowTop, m_data->m_fullWindowWidth, m_data->m_fullWindowHeight, TRUE);

		GetClientRect(m_data->m_hWnd,&clientRect);
		int w = clientRect.right-clientRect.left;
		int h = clientRect.bottom-clientRect.top;
//		printf("actual client OpenGL viewport width / height = %d, %d\n",w,h);
		m_data->m_openglViewportHeight = h;
		m_data->m_openglViewportWidth = w;
		
	}
	else if (windowHandle)
	{
		// attach external window
		m_data->m_hWnd = static_cast<HWND>(windowHandle);
		RECT r;
		GetWindowRect(m_data->m_hWnd, &r);
		m_data->m_fullWindowWidth = r.right - r.left;
		m_data->m_fullWindowHeight= r.bottom - r.top;


		//sFullScreen = false;
		//sExternalWindow = true;
	}


	if (fullscreen)
	{
		DEVMODE dm;
		memset(&dm, 0, sizeof(dm));
		dm.dmSize = sizeof(dm);
		// use default values from current setting
		EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &dm);
		m_data->m_oldScreenWidth = dm.dmPelsWidth;
		m_data->m_oldHeight = dm.dmPelsHeight;
		m_data->m_oldBitsPerPel = dm.dmBitsPerPel;

		dm.dmPelsWidth = oglViewportWidth;
		dm.dmPelsHeight = oglViewportHeight;
		if (colorBitsPerPixel)
		{
			dm.dmBitsPerPel = colorBitsPerPixel;
		}
		dm.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT | DM_DISPLAYFREQUENCY;

		LONG res = ChangeDisplaySettings(&dm, CDS_FULLSCREEN);
		if (res != DISP_CHANGE_SUCCESSFUL)
		{ // try again without forcing display frequency
			dm.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
			res = ChangeDisplaySettings(&dm, CDS_FULLSCREEN);
		}

	}


}
コード例 #24
0
ファイル: win32_v.cpp プロジェクト: xno/openttd-cargodist
/**
 * Instantiate a new window.
 * @param full_screen Whether to make a full screen window or not.
 * @return True if the window could be created.
 */
bool VideoDriver_Win32::MakeWindow(bool full_screen)
{
	_fullscreen = full_screen;

	/* recreate window? */
	if ((full_screen || _wnd.fullscreen) && _wnd.main_wnd) {
		DestroyWindow(_wnd.main_wnd);
		_wnd.main_wnd = 0;
	}

#if defined(WINCE)
	/* WinCE is always fullscreen */
#else
	if (full_screen) {
		DEVMODE settings;

		/* Make sure we are always at least the screen-depth of the blitter */
		if (_fullscreen_bpp < BlitterFactory::GetCurrentBlitter()->GetScreenDepth()) _fullscreen_bpp = BlitterFactory::GetCurrentBlitter()->GetScreenDepth();

		memset(&settings, 0, sizeof(settings));
		settings.dmSize = sizeof(settings);
		settings.dmFields =
			(_fullscreen_bpp != 0 ? DM_BITSPERPEL : 0) |
			DM_PELSWIDTH |
			DM_PELSHEIGHT |
			(_display_hz != 0 ? DM_DISPLAYFREQUENCY : 0);
		settings.dmBitsPerPel = _fullscreen_bpp;
		settings.dmPelsWidth  = _wnd.width_org;
		settings.dmPelsHeight = _wnd.height_org;
		settings.dmDisplayFrequency = _display_hz;

		/* Check for 8 bpp support. */
		if (settings.dmBitsPerPel != 32 && ChangeDisplaySettings(&settings, CDS_FULLSCREEN | CDS_TEST) != DISP_CHANGE_SUCCESSFUL) {
			settings.dmBitsPerPel = 32;
		}

		/* Test fullscreen with current resolution, if it fails use desktop resolution. */
		if (ChangeDisplaySettings(&settings, CDS_FULLSCREEN | CDS_TEST) != DISP_CHANGE_SUCCESSFUL) {
			RECT r;
			GetWindowRect(GetDesktopWindow(), &r);
			/* Guard against recursion. If we already failed here once, just fall through to
			 * the next ChangeDisplaySettings call which will fail and error out appropriately. */
			if ((int)settings.dmPelsWidth != r.right - r.left || (int)settings.dmPelsHeight != r.bottom - r.top) {
				return this->ChangeResolution(r.right - r.left, r.bottom - r.top);
			}
		}

		if (ChangeDisplaySettings(&settings, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL) {
			this->MakeWindow(false);  // don't care about the result
			return false;  // the request failed
		}
	} else if (_wnd.fullscreen) {
		/* restore display? */
		ChangeDisplaySettings(NULL, 0);
		/* restore the resolution */
		_wnd.width = _bck_resolution.width;
		_wnd.height = _bck_resolution.height;
	}
#endif

	{
		RECT r;
		DWORD style, showstyle;
		int w, h;

		showstyle = SW_SHOWNORMAL;
		_wnd.fullscreen = full_screen;
		if (_wnd.fullscreen) {
			style = WS_POPUP;
			SetRect(&r, 0, 0, _wnd.width_org, _wnd.height_org);
		} else {
			style = WS_OVERLAPPEDWINDOW;
			/* On window creation, check if we were in maximize mode before */
			if (_window_maximize) showstyle = SW_SHOWMAXIMIZED;
			SetRect(&r, 0, 0, _wnd.width, _wnd.height);
		}

#if !defined(WINCE)
		AdjustWindowRect(&r, style, FALSE);
#endif
		w = r.right - r.left;
		h = r.bottom - r.top;

		if (_wnd.main_wnd != NULL) {
			if (!_window_maximize) SetWindowPos(_wnd.main_wnd, 0, 0, 0, w, h, SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOMOVE);
		} else {
			TCHAR Windowtitle[50];
			int x = (GetSystemMetrics(SM_CXSCREEN) - w) / 2;
			int y = (GetSystemMetrics(SM_CYSCREEN) - h) / 2;

			_sntprintf(Windowtitle, lengthof(Windowtitle), _T("OpenTTD %s"), MB_TO_WIDE(_openttd_revision));

			_wnd.main_wnd = CreateWindow(_T("OTTD"), Windowtitle, style, x, y, w, h, 0, 0, GetModuleHandle(NULL), 0);
			if (_wnd.main_wnd == NULL) usererror("CreateWindow failed");
			ShowWindow(_wnd.main_wnd, showstyle);
		}
	}

	BlitterFactory::GetCurrentBlitter()->PostResize();

	GameSizeChanged(); // invalidate all windows, force redraw
	return true; // the request succeeded
}
コード例 #25
0
ファイル: CWindow.cpp プロジェクト: ManuelHaertl/triebWerk
bool triebWerk::CWindow::Initialize(const bool a_Fullscreen, const unsigned short a_ScreenWidth, const unsigned short a_ScreenHeight, const SWindowConfig& a_WindowConfig)
{
	if (a_WindowConfig.m_WindowStyle == 0)
	{
		WindowStyleWindowed = DefaultWindowStyleWindowed;
	}
	else
	{
		WindowStyleWindowed = a_WindowConfig.m_WindowStyle;
	}

	if (strlen(a_WindowConfig.m_WindowName) == 0)
	{
		CDebugLogfile::Instance().LogfText(CDebugLogfile::ELogType::Error, false, "Error: Empty window name not allowed!");
		return false;
	}

	//Get the default user screen resolution
	m_DefaultWidth = static_cast<unsigned short>(GetSystemMetrics(SM_CXSCREEN));
	m_DefaultHeight = static_cast<unsigned short>(GetSystemMetrics(SM_CYSCREEN));

	//Set initialize values
	m_Width = a_ScreenWidth;
	m_Height = a_ScreenHeight;
	m_IsFullscreen = a_Fullscreen;

	HMODULE hModule;

	hModule = GetModuleHandle(NULL);

	//window sytle
	WNDCLASSEX mainWindowDescription;
	ZeroMemory(&mainWindowDescription, sizeof(WNDCLASSEX));
	mainWindowDescription.cbSize = sizeof(WNDCLASSEX);
	mainWindowDescription.style = CS_HREDRAW | CS_VREDRAW;
	mainWindowDescription.lpfnWndProc = WindowProcedure;
	mainWindowDescription.hInstance = GetModuleHandle(NULL);
	mainWindowDescription.hCursor = LoadCursor(NULL, IDC_ARROW);
	mainWindowDescription.hbrBackground = (HBRUSH)COLOR_WINDOW;
	mainWindowDescription.lpszClassName = a_WindowConfig.m_WindowName;
	if(a_WindowConfig.m_IconID != 0)
	{
		mainWindowDescription.hIcon = LoadIcon(hModule, MAKEINTRESOURCE(a_WindowConfig.m_IconID));
		mainWindowDescription.hIconSm = mainWindowDescription.hIcon;
	}


	RegisterClassEx(&mainWindowDescription);

	//Adjust the window rect
	RECT windowRectangle = { 0, 0, static_cast<long>(a_ScreenWidth), static_cast<long>(a_ScreenHeight) };

	AdjustWindowRect(&windowRectangle, WindowStyleWindowed, FALSE);

	//Create window 
	m_WindowHandle = CreateWindowEx(NULL,
		a_WindowConfig.m_WindowName,
		a_WindowConfig.m_WindowName,
		WindowStyleWindowed,
		0,
		0,
		windowRectangle.right - windowRectangle.left,
		windowRectangle.bottom - windowRectangle.top,
		NULL,
		NULL,
		GetModuleHandle(NULL),
		this);

	if (m_WindowHandle == NULL)
	{
		CDebugLogfile::Instance().LogfText(CDebugLogfile::ELogType::Error, false, "Error: Could not initialize a window instance");
		return false;
	}


	ShowWindow(m_WindowHandle, SW_SHOWDEFAULT);
	m_ShowCursor = true;

	//If fullscreen change normal "default" window above to fullscreen
	if (a_Fullscreen)
		ChangeWindowSettings(true, m_Width, m_Height);

	unsigned int a;
	unsigned int b;

	GetDPIFromDisplay(&a, &b);

	return true;
}
コード例 #26
0
// Main
int WINAPI WinMain(HINSTANCE instance, HINSTANCE, LPSTR, int cmdShow)
{
    // Register our window class
    WNDCLASSEX wcex = { sizeof(WNDCLASSEX), CS_CLASSDC|CS_DBLCLKS, MessageProc, 0L, 0L, 
                        instance, NULL, NULL, NULL, NULL, "TwDX9", NULL };
    RegisterClassEx(&wcex);

    // Create a window
    const int W = 640;
    const int H = 480;
    BOOL fullscreen = FALSE; // Set to TRUE to run in fullscreen
    RECT rect = { 0, 0, W, H };
    DWORD style = fullscreen ? WS_POPUP : WS_OVERLAPPEDWINDOW;
    AdjustWindowRect(&rect, style, FALSE);
    HWND wnd = CreateWindow("TwDX9", "AntTweakBar simple example using DirectX9", 
                            style, CW_USEDEFAULT, CW_USEDEFAULT, 
                            rect.right-rect.left, rect.bottom-rect.top, NULL, NULL, instance, NULL);
    if( !wnd )
    {
        MessageBox(NULL, "Cannot create window", "Error", MB_OK|MB_ICONERROR);
        return FALSE;
    }
    ShowWindow(wnd, cmdShow);
    UpdateWindow(wnd);

    // Initialize Direct3D
    g_D3D = Direct3DCreate9(D3D_SDK_VERSION);
    if( !g_D3D )
    {
        MessageBox(wnd, "Cannot initialize DirectX", "Error", MB_OK|MB_ICONERROR);
        return FALSE;
    }

    // Create a Direct3D device
    ZeroMemory( &g_D3Dpp, sizeof(D3DPRESENT_PARAMETERS) );
    g_D3Dpp.Windowed = !fullscreen;
    if( fullscreen )
    {
        g_D3Dpp.BackBufferWidth = W;
        g_D3Dpp.BackBufferHeight = H;
    }
    g_D3Dpp.BackBufferCount = 1;
    g_D3Dpp.SwapEffect = D3DSWAPEFFECT_FLIP;
    if( fullscreen )
        g_D3Dpp.BackBufferFormat = D3DFMT_X8R8G8B8;
    else
        g_D3Dpp.BackBufferFormat = D3DFMT_UNKNOWN;
    g_D3Dpp.hDeviceWindow = wnd;

    g_D3Dpp.EnableAutoDepthStencil = TRUE;
    g_D3Dpp.AutoDepthStencilFormat = D3DFMT_D16;
    g_D3Dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
    HRESULT hr = g_D3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, wnd, 
                                     D3DCREATE_SOFTWARE_VERTEXPROCESSING, &g_D3Dpp, &g_D3DDev);
    if( FAILED(hr) )
    {
        //DXTRACE_ERR_MSGBOX("Cannot create DirectX device", hr);
        MessageBox(wnd, "Cannot create DirectX device", "Error", MB_OK|MB_ICONERROR);
        g_D3D->Release();
        g_D3D = NULL;
        return FALSE;
    }

    // This example draws a moving strip;
    // create a buffer of vertices for the strip
    struct Vertex
    {
        float x, y, z;
        DWORD color;
    };
    Vertex vertices[2002];
    int numSec = 100;            // number of strip sections
    float color[] = { 1, 0, 0 }; // strip color
    unsigned int bgColor = D3DCOLOR_ARGB(255, 128, 196, 196); // background color

    // Init some D3D states
    InitD3D();

    // Initialize AntTweakBar
    // (note that the Direct3D device pointer must be passed to TwInit)
    if( !TwInit(TW_DIRECT3D9, g_D3DDev) )
    {
        MessageBox(wnd, TwGetLastError(), "Cannot initialize AntTweakBar", MB_OK|MB_ICONERROR);
        g_D3DDev->Release();
        g_D3DDev = NULL;
        g_D3D->Release();
        g_D3D = NULL;
        return FALSE;
    }

    
    // Create a tweak bar
    TwBar *bar = TwNewBar("TweakBar");
    TwDefine(" GLOBAL help='This example shows how to integrate AntTweakBar in a DirectX9 application.' "); // Message added to the help bar.
    TwDefine(" TweakBar color='128 224 160' text=dark "); // Change TweakBar color and use dark text

    // Add 'numSec' to 'bar': it is a modifiable (RW) variable of type TW_TYPE_INT32. Its shortcuts are [s] and [S].
    TwAddVarRW(bar, "NumSec", TW_TYPE_INT32, &numSec, 
               " label='Strip length' min=1 max=1000 keyIncr=s keyDecr=S help='Number of segments of the strip.' ");

    // Add 'color' to 'bar': it is a modifiable variable of type TW_TYPE_COLOR3F (3 floats color)
    TwAddVarRW(bar, "Color", TW_TYPE_COLOR3F, &color, " label='Strip color' ");

    // Add 'bgColor' to 'bar': it is a modifiable variable of type TW_TYPE_COLOR32 (32 bits color)
    TwAddVarRW(bar, "BgColor", TW_TYPE_COLOR32, &bgColor, " label='Background color' ");

    // Add 'width' and 'height' to 'bar': they are read-only (RO) variables of type TW_TYPE_INT32.
    TwAddVarRO(bar, "Width", TW_TYPE_INT32, &g_D3Dpp.BackBufferWidth, 
               " label='wnd width' help='Current graphics window width.' ");
    TwAddVarRO(bar, "Height", TW_TYPE_INT32, &g_D3Dpp.BackBufferHeight, 
               " label='wnd height' help='Current graphics window height.' ");


    // Main loop
    bool quit = false;
    while( !quit )
    {
        // Clear screen and begin draw
        g_D3DDev->Clear(0, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER, bgColor, 1.0f, 0);
        g_D3DDev->BeginScene();

        // Draw scene
        float s, t = (float)GetTickCount()/1000.0f;
        for( int i=0; i<=numSec; ++i )  // update vertices
        {
            s = (float)i/100;
            vertices[2*i+0].x = 0.05f+0.7f*cosf(2.0f*s+5.0f*t);
            vertices[2*i+1].x = vertices[2*i+0].x + (0.25f+0.1f*cosf(s+t));
            vertices[2*i+0].y = vertices[2*i+1].y = 0.7f*(0.7f+0.3f*sinf(s+t))*sinf(1.5f*s+3.0f*t);
            vertices[2*i+0].z = vertices[2*i+1].z = 0;
            s = (float)i/numSec;
            vertices[2*i+0].color = vertices[2*i+1].color = 
                D3DCOLOR_XRGB((int)(255*color[0]*s), (int)(255*color[1]*s), (int)(255*color[2]*s));
        }
        g_D3DDev->SetFVF(D3DFVF_XYZ|D3DFVF_DIFFUSE);
        g_D3DDev->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2*numSec, vertices, sizeof(Vertex)); // draw strip
 
        // Draw tweak bars
        TwDraw();

        // End draw
        g_D3DDev->EndScene();

        // Present frame buffer
        g_D3DDev->Present(NULL, NULL, NULL, NULL);

        // Process windows messages
        MSG msg;
        while( PeekMessage(&msg, NULL, 0, 0, PM_REMOVE) )
        {
            if( msg.message==WM_QUIT )
                quit = true;
            else if( !TranslateAccelerator(msg.hwnd, NULL, &msg) ) 
            {
                TranslateMessage(&msg);
                DispatchMessage(&msg);
            }
        }
    } // End of main loop


    // Terminate AntTweakBar
    TwTerminate();

    // Release Direct3D
    g_D3DDev->Release();
    g_D3DDev = NULL;
    g_D3D->Release();
    g_D3D = NULL;

    return 0;
}
コード例 #27
0
//用以保持窗口比例不发生改变
//最大化除外
VOID CGameProcedure::KeepWindowFOV(RECT* pRect, UINT dwChanging, UINT dwAnchor)
{
	RECT rectTemp;
	CopyRect(&rectTemp, pRect);

	rectTemp.left -= m_rectFCOffset.left;
	rectTemp.top -= m_rectFCOffset.top;
	rectTemp.right -= m_rectFCOffset.right;
	rectTemp.bottom -= m_rectFCOffset.bottom;

	if(WMSZ_LEFT == dwChanging || WMSZ_RIGHT == dwChanging)
	{
		//宽不变
		rectTemp.bottom = rectTemp.top + (INT)((rectTemp.right-rectTemp.left)*m_fWindowFOV);
	}
	else if(WMSZ_TOP == dwChanging || WMSZ_BOTTOM == dwChanging)
	{
		//高不变
		rectTemp.right = rectTemp.left + (INT)((rectTemp.bottom-rectTemp.top)/m_fWindowFOV);
	}
	else
	{
		//根据比例自动调节
		FLOAT fFov = (FLOAT)(rectTemp.bottom-rectTemp.top)/(FLOAT)(rectTemp.right-rectTemp.left);
		if(fFov > m_fWindowFOV)
		{
			rectTemp.bottom = rectTemp.top + (INT)((rectTemp.right-rectTemp.left)*m_fWindowFOV);
		}
		else
		{
			rectTemp.right = rectTemp.left + (INT)((rectTemp.bottom-rectTemp.top)/m_fWindowFOV);
		}
	}

	AdjustWindowRect(&rectTemp, DEFWINDOW_STYLE, FALSE);

	switch(dwAnchor)
	{
	case WMSZ_TOPLEFT:
		{
			pRect->right = pRect->left + (rectTemp.right-rectTemp.left);
			pRect->bottom = pRect->top + (rectTemp.bottom-rectTemp.top);
		}
		break;

	case WMSZ_TOPRIGHT:
		{
			pRect->left = pRect->right - (rectTemp.right-rectTemp.left);
			pRect->bottom = pRect->top + (rectTemp.bottom-rectTemp.top);
		}
		break;

	case WMSZ_BOTTOMLEFT:
		{
			pRect->right = pRect->left + (rectTemp.right-rectTemp.left);
			pRect->top = pRect->bottom - (rectTemp.bottom-rectTemp.top);
		}
		break;

	case WMSZ_BOTTOMRIGHT:
		{
			pRect->left = pRect->right - (rectTemp.right-rectTemp.left);
			pRect->top = pRect->bottom - (rectTemp.bottom-rectTemp.top);
		}
		break;
	}
}
コード例 #28
0
ファイル: WinSystemWin32.cpp プロジェクト: blacksocket/xbmc
bool CWinSystemWin32::ResizeInternal(bool forceRefresh)
{
    if (m_hWnd == NULL)
        return false;
    DWORD dwStyle = WS_CLIPCHILDREN;
    HWND windowAfter;
    RECT rc;

    if(m_bFullScreen)
    {
        dwStyle |= WS_POPUP;
        windowAfter = HWND_TOP;
        rc = ScreenRect(m_nScreen);
    }
    else
    {
        dwStyle |= WS_OVERLAPPEDWINDOW;
        windowAfter = g_advancedSettings.m_alwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST;

        rc.left = m_nLeft;
        rc.right = m_nLeft + m_nWidth;
        rc.top = m_nTop;
        rc.bottom = m_nTop + m_nHeight;

        HMONITOR hMon = MonitorFromRect(&rc, MONITOR_DEFAULTTONULL);
        HMONITOR hMon2 = MonitorFromWindow(m_hWnd, MONITOR_DEFAULTTOPRIMARY);

        // hasn't been windowed yet, or windowed position would not fullscreen to the same screen we were fullscreen on?
        // -> center on the screen that we were fullscreen on
        if(!m_ValidWindowedPosition || hMon == NULL || hMon != hMon2)
        {
            RECT newScreenRect = ScreenRect(GetCurrentScreen());
            rc.left = m_nLeft = newScreenRect.left + ((newScreenRect.right - newScreenRect.left) / 2) - (m_nWidth / 2);
            rc.top  = m_nTop  =  newScreenRect.top + ((newScreenRect.bottom - newScreenRect.top) / 2) - (m_nHeight / 2);
            rc.right = m_nLeft + m_nWidth;
            rc.bottom = m_nTop + m_nHeight;
        }

        AdjustWindowRect( &rc, WS_OVERLAPPEDWINDOW, false );
    }

    WINDOWINFO wi;
    wi.cbSize = sizeof (WINDOWINFO);
    if(!GetWindowInfo(m_hWnd, &wi))
    {
        CLog::Log(LOGERROR, "%s : GetWindowInfo failed with %d", __FUNCTION__, GetLastError());
        return false;
    }
    RECT wr = wi.rcWindow;

    if (forceRefresh || wr.bottom  - wr.top != rc.bottom - rc.top || wr.right - wr.left != rc.right - rc.left ||
            (wi.dwStyle & WS_CAPTION) != (dwStyle & WS_CAPTION))
    {
        CLog::Log(LOGDEBUG, "%s - resizing due to size change (%d,%d,%d,%d%s)->(%d,%d,%d,%d%s)",__FUNCTION__,wr.left, wr.top, wr.right, wr.bottom, (wi.dwStyle & WS_CAPTION) ? "" : " fullscreen",
                  rc.left, rc.top, rc.right, rc.bottom, (dwStyle & WS_CAPTION) ? "" : " fullscreen");
        SetWindowRgn(m_hWnd, 0, false);
        SetWindowLong(m_hWnd, GWL_STYLE, dwStyle);

        // The SWP_DRAWFRAME is here because, perversely, without it win7 draws a
        // white frame plus titlebar around the xbmc splash
        SetWindowPos(m_hWnd, windowAfter, rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top, SWP_SHOWWINDOW|SWP_DRAWFRAME);

        // TODO: Probably only need this if switching screens
        ValidateRect(NULL, NULL);
    }
    return true;
}
コード例 #29
0
//缺省消息响应函数,可被相应的流程继承
LRESULT CGameProcedure::MainWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	//--------------------------------------------------------------
	//处理一些缺省的消息
	switch (message) 
	{
	//窗口大小发生改变
	case WM_SIZE:
		{
			//最小化
            if( SIZE_MINIMIZED == wParam )
            {
                m_bRenderingPaused = true; // 最小化时渲染暂停

                m_bMinimized = true;
				m_bMaximized = FALSE;
            }
			//最大化
            else if( SIZE_MAXIMIZED == wParam )
            {
                m_bRenderingPaused = FALSE; //恢复渲染工作(可能上一个状态时最小化)

				m_bMinimized = FALSE;
				m_bMaximized = true;
				HandlePossibleSizeChange( message, wParam, lParam);
			}
			//恢复窗口
            else if( SIZE_RESTORED == wParam )
            {
                if( m_bMaximized )	//刚才是最大化
                {
                    m_bMaximized = FALSE;
                    HandlePossibleSizeChange(message, wParam, lParam);
                }
                else if( m_bMinimized )	//刚才是最小化
                {
                    m_bRenderingPaused = FALSE; 

					m_bMinimized = FALSE;
                    HandlePossibleSizeChange(message, wParam, lParam);
                }
                else
                {
					//如果上一个状态既不是最大化也不是最小化,显然这次的WM_SIZE
					//消息是因为用户拖动窗口边缘引起的,这种情况我们并不马上恢复
					//设备,我们等待用户停止拖动后在处理,也就是对WM_EXITSIZEMOVE
					//的处理...
                }
            }
		}
		break;

	//用户拖动窗口开始
	case WM_ENTERSIZEMOVE:
		{
			m_bRenderingPaused = true;
		}
		break;
	//用户拖动中
	case WM_SIZING:
		{
			RECT* pRect = (RECT*)lParam;

			switch(wParam)
			{
			case WMSZ_RIGHT:
			case WMSZ_BOTTOMRIGHT:
				{
					KeepWindowFOV(pRect, WMSZ_RIGHT, WMSZ_TOPLEFT);
				}
				break;
			case WMSZ_LEFT:
			case WMSZ_BOTTOMLEFT:
				{
					KeepWindowFOV(pRect, WMSZ_LEFT, WMSZ_TOPRIGHT);
				}
				break;

			case WMSZ_TOP:
 			case WMSZ_TOPRIGHT:
				{
					KeepWindowFOV(pRect, WMSZ_TOP, WMSZ_BOTTOMLEFT);
				}
				break;

			case WMSZ_BOTTOM:
				{
					KeepWindowFOV(pRect, WMSZ_BOTTOM, WMSZ_TOPLEFT);
				}
				break;

			case WMSZ_TOPLEFT:
				{
					KeepWindowFOV(pRect, WMSZ_TOP, WMSZ_BOTTOMRIGHT);
				}
				break;
			}
			return TRUE;
		}
		break;
	//窗口尺寸发生了改变后
	case WM_WINDOWPOSCHANGING:
		// fujia 2008.1.23 防止窗口模式窗口大小发生变化
		//{    
		//	WINDOWPOS* pPos = (WINDOWPOS*)lParam;
		//	//非大小改变
		//	if(pPos->flags & SWP_NOSIZE || pPos->flags & SWP_DRAWFRAME) break;
		//	//是“全屏”状态
		//	if(s_pVariableSystem && 
		//		s_pVariableSystem->GetAs_Int("View_FullScreen")) break;

		//	//计算新的Client
		//	RECT rectFrame;
		//	SetRect(&rectFrame, 0, 0, pPos->cx, pPos->cy);
		//	OffsetRect(&rectFrame, pPos->x, pPos->y);

		//	RECT rectNewFrame;
		//	CopyRect(&rectNewFrame, &rectFrame);
		//	KeepWindowFOV(&rectNewFrame, -1, WMSZ_TOPLEFT);

		//	//如果相同不处理
		//	if(EqualRect(&rectFrame, &rectNewFrame)) break;

		//	pPos->x = rectNewFrame.left;
		//	pPos->y = rectNewFrame.top;
		//	pPos->cx = rectNewFrame.right-rectNewFrame.left;
		//	pPos->cy = rectNewFrame.bottom-rectNewFrame.top;

		//	return 0;
		//}
		break;

	//桌面分辨率改变
	case WM_DISPLAYCHANGE:
		{
			if( s_pEventSystem && s_pVariableSystem->GetAs_Int("View_FullScreen"))
			{
				s_pEventSystem->PushEvent(GE_VARIABLE_CHANGED, "View_FullScreen", "1");
			}
			//重置分辨率
			if(m_bMaximized)
			{
				ShowWindow(g_hMainWnd, SW_RESTORE);
				ShowWindow(g_hMainWnd, SW_MAXIMIZE);
			}
			else 
			{
				s_pEventSystem->PushEvent(GE_VARIABLE_CHANGED, "View_Resoution", 
					s_pVariableSystem->GetAs_String("View_Resoution").c_str());
			}
			break;
		}
	//用户拖动窗口边缘结束
	case WM_EXITSIZEMOVE:
		{
			m_bRenderingPaused = FALSE;
			HandlePossibleSizeChange(message, wParam, lParam);

			//设置分辨率变量
			if(s_pVariableSystem)
			{
				RECT rect;
				GetClientRect(hWnd, &rect);
				char szTemp[MAX_PATH];
				_snprintf(szTemp, MAX_PATH, "%d,%d", rect.right-rect.left, rect.bottom-rect.top);

				s_pVariableSystem->SetVariable("View_Resoution", szTemp, FALSE, FALSE);
				
			}
		}
		break;

	//决定窗口最大最小尺寸
	case WM_GETMINMAXINFO:
		{
			MINMAXINFO* pMinMaxInfo = (MINMAXINFO*)lParam;

			pMinMaxInfo->ptMinTrackSize.x = MINWINDOW_WIDTH;
			pMinMaxInfo->ptMinTrackSize.y = MINWINDOW_HEIGHT;

			//最大尺寸为“窗口最大化”时的大小
			RECT rect;
			SetRect(&rect, 0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN));
			AdjustWindowRect(&rect, GetWindowStyle(g_hMainWnd), FALSE);

			pMinMaxInfo->ptMaxSize.x = rect.right-rect.left;
			pMinMaxInfo->ptMaxSize.y = rect.bottom-rect.top;

			pMinMaxInfo->ptMaxTrackSize.x = rect.right-rect.left;
			pMinMaxInfo->ptMaxTrackSize.y = rect.bottom-rect.top;
		}
		break;

	//设置光标
	case WM_SETCURSOR:
		{
			switch(LOWORD(lParam))
			{
			case HTCLIENT:
				{
					if(s_pCursorMng)
					{
						s_pCursorMng->OnSetCursor();
						return TRUE;
					}
				}
				break;

			default:
				break;
			}
		}
		break;

	//窗口激活切换
	case WM_ACTIVATEAPP:
		if( wParam == TRUE )
		{
			m_bActive = TRUE;
		}
		else 
		{
			m_bActive = FALSE;
		}
		//通知输入器
		if(s_pInputSystem) ((CInputSystem*)s_pInputSystem)->OnActiveApp(m_bActive);
		break;
	//消息主循环移到菜单中
	case WM_ENTERMENULOOP:
		{
			m_bRenderingPaused = true;
		}
		break;

	//消息主循环移出菜单
	case WM_EXITMENULOOP:
		{
			m_bRenderingPaused = FALSE;
		}
		break;
	
	//系统按键
	case WM_SYSCOMMAND:
		{
			switch(wParam)
			{
			//屏蔽F10
			case SC_KEYMENU:
				return 1;

			default:
				break;
			}
		}
		break;
	
	//窗口重绘消息
	case WM_PAINT:
		{
			PAINTSTRUCT psStruct;
			::BeginPaint(hWnd, &psStruct);
			::EndPaint(hWnd, &psStruct);
			s_pGfxSystem->OnPaint();

		}
		break;

	//窗口背景刷
	case WM_ERASEBKGND:
		{
			return 1;
		}
		break;

	//处理玩家的退出请求
	case WM_CLOSE:
		{
			//主流程中,弹出设置菜单
			if(GetActiveProcedure() == s_pProcMain && s_pUISystem)
			{
				if(wParam==0xC0DE && lParam==0XC0DE)
				{
					ProcessCloseRequest();
					break;
				}
				else
				{
					s_pEventSystem->PushEvent( GE_TOGLE_SYSTEMFRAME );
					return TRUE;
				}
			}
		}
		break;
	//窗口销毁
	case WM_DESTROY:
		{
			PostQuitMessage(0);
		}
		break;
	//输入法改变
	case WM_INPUTLANGCHANGE:
		{
			if(s_pEventSystem)
			{
				s_pEventSystem->PushEvent(GE_CHAT_INPUTLANGUAGE_CHANGE);
			}
		}
		break;
	case WM_IME_NOTIFY:
		{
			if(wParam == IMN_SETOPENSTATUS || wParam == IMN_SETCONVERSIONMODE)
			{
				if(s_pEventSystem)
				{
					s_pEventSystem->PushEvent(GE_CHAT_INPUTLANGUAGE_CHANGE);
				}
			}
		}
		break;
	default:
		break;
	}

	return DefWindowProc( hWnd, message, wParam, lParam );
}
コード例 #30
0
ファイル: wwnd.c プロジェクト: AntonLanghoff/whitecatlib
/* adjust_window:
 *  Moves and resizes the window if we have full control over it.
 */
int adjust_window(int w, int h)
{
   RECT working_area, win_size;
   TITLEBARINFO tb_info;
   HMODULE user32_handle;
   typedef BOOL (WINAPI *func)(HWND, PTITLEBARINFO);
   func get_title_bar_info = NULL;
   int tb_height = 0;
   static int last_w=-1, last_h=-1;

   if (!user_wnd) {
      SystemParametersInfo(SPI_GETWORKAREA, 0, &working_area, 0);

      if ((last_w == -1) && (last_h == -1)) {
         /* first window placement: try to center it */
         last_wnd_x = (working_area.left + working_area.right - w)/2;
         last_wnd_y = (working_area.top + working_area.bottom - h)/2;
      }
      else {
         /* try to get the height of the window's title bar */
         user32_handle = GetModuleHandle("user32");
         if (user32_handle) {
            get_title_bar_info
               = (func)GetProcAddress(user32_handle, "GetTitleBarInfo");
            if (get_title_bar_info) {
               tb_info.cbSize = sizeof(TITLEBARINFO);
               if (get_title_bar_info(allegro_wnd, &tb_info))
                  tb_height
                     = tb_info.rcTitleBar.bottom - tb_info.rcTitleBar.top;
            }
         }
         if (!user32_handle || !get_title_bar_info)
            tb_height = GetSystemMetrics(SM_CYSIZE);
         
	 /* try to center the window relative to its last position */
	 last_wnd_x += (last_w - w)/2;
	 last_wnd_y += (last_h - h)/2;
	 
	 if (last_wnd_x + w >= working_area.right)
	    last_wnd_x = working_area.right - w;
	 if (last_wnd_y + h >= working_area.bottom)
	    last_wnd_y = working_area.bottom - h;
	 if (last_wnd_x < working_area.left)
	    last_wnd_x = working_area.left;
	 if (last_wnd_y - tb_height < working_area.top)
	    last_wnd_y = working_area.top + tb_height;
      }

#ifdef ALLEGRO_COLORCONV_ALIGNED_WIDTH
      last_wnd_x &= 0xfffffffc;
#endif

      win_size.left = last_wnd_x;
      win_size.top = last_wnd_y;
      win_size.right = last_wnd_x+w;
      win_size.bottom = last_wnd_y+h;

      last_w = w;
      last_h = h;

      /* retrieve the size of the decorated window */
      AdjustWindowRect(&win_size, GetWindowLong(allegro_wnd, GWL_STYLE), FALSE);
   
      /* display the window */
      MoveWindow(allegro_wnd, win_size.left, win_size.top,
                 win_size.right - win_size.left, win_size.bottom - win_size.top, TRUE);

      /* check that the actual window size is the one requested */
      GetClientRect(allegro_wnd, &win_size);
      if (((win_size.right - win_size.left) != w) || ((win_size.bottom - win_size.top) != h))
         return -1;

      wnd_x = last_wnd_x;
      wnd_y = last_wnd_y;
      wnd_width = w;
      wnd_height = h;
   }

   return 0;
}