void Game::RenderThreadloop() { CA_TRACE("Renderer initialized\n"); Initialize(); CA_TRACE("Game initialized\n"); LoadContent(); CA_TRACE("Game load content done\n"); try { BeginRun(); #if CA_PLATFORM_DESKTOP FrameLoop(); EndRun(); #endif // #if CA_PLATFORM_DESKTOP } catch (const std::exception& ex) { CA_FATAL("Error during game running : %s", ex.what()); return; } catch (...) { CA_FATAL("Error during game running : generic exception"); return; } }
bool CD3DWater::Create(float iSizeX, float iSizeY, float iPosX , // 横坐标 float iPosY , // 纵坐标 float iHeight ) { if (!LoadContent()) return false; FetchSurfaces();//获得折射反射渲染表面 if (FAILED(m_pDevice->CreateVertexBuffer(6 * sizeof(VertexPositionTex), D3DUSAGE_WRITEONLY, VertexPositionTex::FVF, D3DPOOL_DEFAULT, &m_pVB, 0))) return false; VertexPositionTex* pVertices; m_pVB->Lock(0, 0, (void**)&pVertices, 0); pVertices[0] = VertexPositionTex{ iPosX, iHeight, iPosY + iSizeY, 0, 0 }; pVertices[1] = VertexPositionTex{ iPosX + iSizeX, iHeight, iPosY + iSizeY, 1, 0 }; pVertices[2] = VertexPositionTex{ iPosX, iHeight, iPosY, 0, 1 }; pVertices[3] = VertexPositionTex{ iPosX + iSizeX, iHeight, iPosY + iSizeY, 1, 0 }; pVertices[4] = VertexPositionTex{ iPosX + iSizeX, iHeight, iPosY, 1, 1 }; pVertices[5] = VertexPositionTex{ iPosX, iHeight, iPosY, 0, 1 }; m_pVB->Unlock(); //设置摄像机反射面 //创建折射 反射横切面 D3DXPlaneFromPointNormal(&m_waterPlane, &D3DXVECTOR3(iPosX, iHeight, iPosY), &D3DXVECTOR3(0,1,0)); D3DXPlaneNormalize(&m_waterPlane, &m_waterPlane); return true; }
int main(int argc, char *argv[]) { displayWindow = SDL_CreateWindow("Jello", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREENWIDTH, SCREENHEIGHT, SDL_WINDOW_OPENGL); context = SDL_GL_CreateContext(displayWindow); glOrtho(-SCREENWIDTH / 2, SCREENWIDTH / 2, SCREENHEIGHT / 2, -SCREENHEIGHT / 2, 0, 1); LoadContent(); while (isRunning) { RemoveInitialPress(); leftButtonPress = false; while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) isRunning = false; GetKeys(event); GetButtons(event); } if (deltaTime < 1 / 60) { frameStart = SDL_GetTicks(); SDL_Delay(1); frameEnd = SDL_GetTicks(); deltaTime = frameEnd - frameStart; } frameStart = SDL_GetTicks(); Update(deltaTime); Render(displayWindow, context); frameEnd = SDL_GetTicks(); deltaTime = frameEnd - frameStart; } return 0; }
void Game::Run() { //if the game object fail to load then return before the loop is entered if(!LoadContent()) { MessageBoxA(NULL, "Failed to load game objects", "ERROR!", MB_OK | MB_ICONERROR); return; } //Initalise the game timer m_system.GetGameTimer()->Reset(); //The game loop is open until the system gets a WM_QUIT msg while(!m_system.Done() && !m_escape) { //starts the game timer m_system.GetGameTimer()->Tick(); //Detect input m_system.GetDirectInput()->DetectInput(); //Update the game Update(m_system.GetGameTimer()->GetDeltaTime()); //change wireframe mode m_system.GetDX()->SetWireframeMode(m_wireframe); Render(); } //Unload all the objects after the loop has closed UnloadContent(); }
//DO NOT MODIFY MAIN int main(int argv, char** argc) { Initialize(); LoadContent(); float timeThisFrame = 0; float timeLastFrame = 0; float deltaTime = 0; //DO NOT MODIFY THIS METHOD do { //Set lastframe time to this frames time timeLastFrame = timeThisFrame; //Set this frame time to time since starting the program timeThisFrame = (float)SDL_GetTicks(); //Get the number of seconds that have passed since last frame deltaTime = (timeThisFrame - timeLastFrame) / 1000; //Update the game Update(deltaTime); //Draw the game Draw(); } while (!quit); DestroyGame(); return 0; }
bool Client::OnInit() { if ( SDLNet_Init() == -1 ) { cout << "\nSDLNet_Init failed : " << SDLNet_GetError() << endl; return false; } if ( SDL_Init(SDL_INIT_EVERYTHING) == -1) { cout<< "\nSDL_Init failed : " << SDL_GetError() <<endl; return false; } if((Window = SDL_CreateWindow("Client", 300, 300, 640, 480, SDL_WINDOW_SHOWN)) == NULL) { cout<< "\nSDL_CreateWindow failed : " << SDL_GetError() <<endl; return false; } if((Renderer = SDL_CreateRenderer(Window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC)) == NULL) { cout <<"\nSDL_CreateRenderer failed : "<< SDL_GetError() << endl; return false; } if(LoadContent() == false) { cout<< "\nLoadContent failed" <<endl; return false; } return true; }
QVector<qint32> getStat(QString s) { QVector<qint32> v; QDomElement root = LoadContent(); QDomNodeList items = root.elementsByTagName("Entry"); if(items.count() > 0) { for(int i=0; i<items.count(); i++) { QDomNode itemnode = items.at(i); if(itemnode.isElement()) { QDomElement itemele = itemnode.toElement(); if(s=="K" || s=="k") v.append(itemele.attribute("K").toInt()); if(s=="D" || s=="d") v.append(itemele.attribute("D").toInt()); if(s=="A" || s=="a") v.append(itemele.attribute("A").toInt()); } } } else qDebug() << "There are no any elements"; return v; }
bool Game::Run() { SplashScreen(); LoadScreen(); Initialize(); _currentState=_pMenu; //_currentState = new Level1(_rWindow,_rSfmlDebugDraw,_pWorld,score); LoadContent(); Clock timeElapsed; while ( _rWindow.isOpen() ) { _rWindow.pollEvent(e); if ( e.type == Event::Closed ) { _rWindow.close(); UnloadContent(); break; } if(e.type==Event::KeyPressed) { if(Keyboard::isKeyPressed(Keyboard::LAlt) && Keyboard::isKeyPressed(Keyboard::F4)) { _rWindow.close(); UnloadContent(); break; } } HandleInput( e ); //Time lastUpdateCall = timeElapsed.restart(); if ( timeElapsed.getElapsedTime().asMilliseconds() >= timeStep) { Update( e, oldEvent, timeElapsed.restart() ); } Time lastDrawCall = /*lastUpdateCall +*/ timeElapsed.getElapsedTime(); //.restart(); Draw( _rWindow, lastDrawCall ); oldEvent = e; } return true; }
GameOverScreen::GameOverScreen(sf::RenderWindow *rt) : GameScreen(rt) { input = new InputManager(); LoadContent(); }
int main(int argc, char const *argv[]) { AGE_Init("AGE Test", SCREEN_WIDTH, SCREEN_HEIGHT, false); // AGE_FullScreenBorderless(); Initialize(); LoadContent(); AGE_Run(EventHandler, Update, Draw); Unload(); AGE_Close(); return 0; }
// // ISideShowContent methods // HRESULT CBaseContent::GetContent( ISideShowCapabilities* /*pICapabilities*/, DWORD *pdwSize, BYTE **ppbData) { HRESULT hr = S_OK; DWORD dwSize = 0; BYTE* pbData = NULL; // // Call the subclass to retrieve the // content and size to add. // LoadContent(&dwSize, &pbData); if (NULL != pbData) { // // COM requires memory passed out to be alloc'ed by // CoTaskMemAlloc. Allocate enough to hold the // data returned by the subclass and then copy // the data into the new buffer. // BYTE* pbBuf = (BYTE*)::CoTaskMemAlloc(dwSize); if (NULL != pbBuf) { memcpy(pbBuf, pbData, dwSize); // // Assuming all went well, return the // information to the platform. // *pdwSize = dwSize; *ppbData = pbBuf; } else { hr = E_OUTOFMEMORY; } // // Call the subclass to free the data; // pbData is no longer valid after this call // FreeContent(&pbData); pbData = NULL; } else { hr = E_UNEXPECTED; } return hr; }
bool Game::Initialize() { graphicsDevice = new glGraphicsDevice(); graphicsDevice->Params.BackBufferWidth = Window::Width; graphicsDevice->Params.BackBufferHeight = Window::Height; graphicsDevice->Initialize(); glClearColor(1, 1, 1, 1); return LoadContent(); }
void Game::Initialize() { graphicsService = (IGraphicsDeviceService *)services.GetService(IGraphicsDeviceService::GetType()); for (int i = 0; i < components.Count(); i++) { components[i]->Initialize(); } XInput_Init(); LoadContent(); }
Game::Game(int fps, int width, int height) { mWidth = width; mHeight = height; mFPS = fps; GameGlobal::SetWidth(width); GameGlobal::SetHeight(height); InitInput(); Scene *newScene = new TestScene(); SceneManager::GetInstance()->ReplaceScene(newScene); LoadContent(); InitLoop(); }
void Init_All() { Init_Graphics(); InitSpriteList(); Init_Audio(); InitSoundList(); atexit(CleanUpAll); LoadFonts(); InitMessages(); LoadMouse(Cyan,Gold,DarkViolet); InitEntityList(); ResetAllParticles(); DrawSplashScreen(); LoadContent(); NewMap(32, 48,0,15); DrawMap(); }
LRESULT Client::HandleEvent(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch (msg) { case WM_SOCKET: sPlayerMain.OnSocketEvent(wParam, WSAGETSELECTERROR(lParam), WSAGETSELECTEVENT(lParam)); return 0; case WM_CREATE: LoadContent(); return 0; case WM_KEYDOWN: KeyDown(wParam); return 0; case WM_PAINT: Draw(hwnd); return 0; case WM_LBUTTONDBLCLK: MouseLDButtonDown(lParam); return 0; case WM_MBUTTONDOWN: MouseMButtonDown(lParam); return 0; case WM_LBUTTONDOWN: MouseLButtonDown(lParam); return 0; case WM_RBUTTONDOWN: MouseRButtonDown(lParam); return 0; case WM_MOUSEMOVE: MouseMove(lParam); return 0; case WM_DESTROY: PostQuitMessage(0); return 0; } return DefWindowProc(hwnd, msg, wParam, lParam); }
//============================================================================================================= void CGame10::Run() { bool success = Initialize(); dassert(, "CGame10::Run(): Initialization failed", success); success = LoadContent(); dassert(, "CGame10::Run(): Content creation failed", success); dsad("Most of the features are not yet implemented"); ResetRenderStates(); Sync.Timer().Start(); Application.Show(); valid = false; while( Application.Run() ) { if( Application.Active() ) { if( !valid ) { valid = Validate(); } else { if( fixedtimestep ) Sync.Update(); else Update(); Draw(); } } else { valid = false; Sleep(100); } } UnloadContent(); }
void SpaceSim::Initialize() { done= false; FPS=0; total_frames=0; previous_tick_timestamp =0; elapsed_time=0; old_time=0; dt = .05; doubledt = dt*5; accumulator = 0.0; LoadContent(); CreateWorld(); Update(); };
bool CPlantCollect::Create(float fMinHeight, float fMaxHeight, float fdensity) { m_fMinHeight = fMinHeight; m_fMaxHeight = fMaxHeight; m_fDensity = fdensity; if (!LoadContent()) { Release(); return false; } //创建植被结点 CreatePlantNode(); //创建顶点缓冲 CreateVertices(); return true; }
void ConsoleGame::Initialize() { #if !defined(PLATFORM_WINDOWS) // Catch signals such as CTRL-C struct sigaction sigIntHandler; sigIntHandler.sa_handler = SignalHandler; sigemptyset(&sigIntHandler.sa_mask); sigIntHandler.sa_flags = 0; sigaction(SIGINT, &sigIntHandler, NULL); #endif GameTime::InitClock(); UDPSocket::InitializeSocketLayer(); time.TotalGameTime = GameTime::GetSystemTime(); currentTime = GameTime::GetSystemTime(); dt = 1.0 / targetUpdateFramesPerSecond; LoadContent(); }
void DataFileDB::Attach(const Data& init, const string& variablename,FileDBType type) { dir=savedir+"/"+variablename+"-db"; dbtype=DatabaseExist(); security.WriteFile(dir); if(dbtype!=DBNone) { Dump("DataFileDB::Attach(const Data&, const string&, FileDBType)","load old",init); LoadContent(); } else { dbtype=type; Dump("DataFileDB::Attach(const Data&, const string&, FileDBType)","create new",init); CreateEmpty(); DataFileDB::operator=(init); MarkAllDirty(); } }
int __stdcall WinMain( _In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPSTR lpCmdLine, _In_ int nShowCmd) { // 初始化Instance,创建窗口,初始化d3d工作 HRESULT hr = 0; hr = InitInstance(hInstance, g_WndWidth, g_WndHeight, true, false, g_DevType, &g_pDevice); if (FAILED(hr)) { MessageBox(0, "Faile to init instance!", 0, 0); return 0 ; } // 保存窗口句柄 g_hWnd = GetActiveWindow(); if (!g_hWnd) { MessageBox(0, "Failed to get windows handle!", 0, 0); return 0; } // 游戏设置 hr = SetUp(); if (FAILED(hr)) goto Clean; // 加载游戏内容 hr = LoadContent(); if (FAILED(hr)) goto UnLoad; // 游戏循环 EnterMsgLoop(); // 卸载游戏内容 UnLoad: UnLoadContent(); // 清除 Clean: CleanUp(); return 0; }
bool AddStats(qint8 K, qint8 D, qint8 A) { QDomElement content = LoadContent(); if(file.open(QIODevice::WriteOnly | QIODevice::Text)) { if(content.isElement()) content.appendChild(createStat(K,D,A)); else qDebug() << "The root wasn't found"; qDebug() << doc.toString(); QTextStream stream(&file); stream << doc.toString(); file.close(); return true; } return false; }
int game::OnExecute() { if(OnInit() == false) { return -1; } if(LoadContent() == false) { return -1; } while(Running) { while(SDL_PollEvent(&Event)) { OnEvent(&Event); } OnLoop(); OnRender(); } OnCleanup(); return 0; }
//Initializes the main menu. Calls Load Content if necessary. //Will not succeed if font is not properly loaded. Must be called //following the constructor void MainMenu::Initialize() { //If the font hasn't been loaded yet (its static) if(ButtonFont < 0) { //Load it LoadContent(); } //Make sure we have a valid font to use if(ButtonFont >= 0) { loginButton = new MenuButton(50, 50, 150, 70, -1, "", "LOGIN", ButtonFont); playGameButton = new MenuButton(50, 150, 150, 70, -1, "", "PLAY", ButtonFont); logoutButton = new MenuButton(50, 250, 150, 70, -1, "", "LOGOUT", ButtonFont); statsButton = new MenuButton(50, 350, 150, 70, -1, "", "STATS", ButtonFont); //Add Left Click Event Listener to Login Button loginButton->AddEventHandler(MenuButton::ButtonEvents::LeftClick, &MainMenu::LoginClickListener, this); //Add Mouse Enter Event Listener to Login Button loginButton->AddEventHandler(MenuButton::ButtonEvents::MouseEnter, &MainMenu::LoginMouseEnterListener, this); //Add Mouse Exit Event Listener to Login Button loginButton->AddEventHandler(MenuButton::ButtonEvents::MouseExit, &MainMenu::LoginMouseExitListener, this); //Add Left Click Event Listener to Play Game Button playGameButton->AddEventHandler(MenuButton::ButtonEvents::LeftClick, &MainMenu::PlayGameClickListener, this); //Add Mouse Enter Event Listener to Play Game Button playGameButton->AddEventHandler(MenuButton::ButtonEvents::MouseEnter, &MainMenu::PlayGameMouseEnterListener, this); //Add Mouse Exit Event Listener to Play Game Button playGameButton->AddEventHandler(MenuButton::ButtonEvents::MouseExit, &MainMenu::PlayGameMouseExitListener, this); //Add Left Click Event Listener to Play Game Button logoutButton->AddEventHandler(MenuButton::ButtonEvents::LeftClick, &MainMenu::LogoutClickListener, this); //Add Mouse Enter Event Listener to Play Game Button logoutButton->AddEventHandler(MenuButton::ButtonEvents::MouseEnter, &MainMenu::LogoutMouseEnterListener, this); //Add Mouse Exit Event Listener to Play Game Button logoutButton->AddEventHandler(MenuButton::ButtonEvents::MouseExit, &MainMenu::LogoutMouseExitListener, this); //Add Left Click Event Listener to Play Game Button statsButton->AddEventHandler(MenuButton::ButtonEvents::LeftClick, &MainMenu::StatsClickListener, this); //Add Mouse Enter Event Listener to Play Game Button statsButton->AddEventHandler(MenuButton::ButtonEvents::MouseEnter, &MainMenu::StatsMouseEnterListener, this); //Add Mouse Exit Event Listener to Play Game Button statsButton->AddEventHandler(MenuButton::ButtonEvents::MouseExit, &MainMenu::StatsMouseExitListener, this); } }
//初始化 bool Dx11DemoBase::Initialize( HINSTANCE hInstance , HWND hwnd ) { hInstance_ = hInstance; hwnd_ = hwnd; RECT dimensions;//创建矩形对象 //获取窗口客户区 GetClientRect( hwnd , &dimensions ); unsigned int width = dimensions.right - dimensions.left; unsigned int height = dimensions.bottom - dimensions.top; D3D_DRIVER_TYPE driverTypes[] = { D3D_DRIVER_TYPE_HARDWARE, D3D_DRIVER_TYPE_WARP, D3D_DRIVER_TYPE_SOFTWARE }; unsigned int totalDriverTypes = ARRAYSIZE( driverTypes ); D3D_FEATURE_LEVEL featureLevels[] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0 }; unsigned int totalFeatureLevels = ARRAYSIZE( featureLevels ); DXGI_SWAP_CHAIN_DESC swapChainDesc; ZeroMemory( &swapChainDesc , sizeof( swapChainDesc )); swapChainDesc.BufferCount = 1; swapChainDesc.BufferDesc.Width = width; swapChainDesc.BufferDesc.Height = height; swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;//specfic the Format swapChainDesc.BufferDesc.RefreshRate.Numerator = 60; swapChainDesc.BufferDesc.RefreshRate.Denominator = 1; swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swapChainDesc.OutputWindow = hwnd; swapChainDesc.Windowed = true; swapChainDesc.SampleDesc.Count = 1; swapChainDesc.SampleDesc.Quality = 0; unsigned int creationFlags = 0; //Create the DirectX 11 device,context,swapchain #ifdef _DEBUG creationFlags |= D3D11_CREATE_DEVICE_DEBUG; #endif HRESULT result; unsigned int driver = 0 ; for( driver = 0; driver < totalDriverTypes; ++driver ) { result = D3D11CreateDeviceAndSwapChain( 0, driverTypes[driver], 0, creationFlags, featureLevels, totalFeatureLevels, D3D11_SDK_VERSION, &swapChainDesc, &swapChain_, &d3dDevice_, &featureLevel_, &d3dContext_ ); if( SUCCEEDED( result ) ) { driverType_ = driverTypes[ driver ]; break; } } if( FAILED( result )) { DXTRACE_MSG( "Failed to create the Direct3D device!" ); return false; } //Render TargetView Creation ID3D11Texture2D * backBufferTexture; result = swapChain_->GetBuffer( 0, __uuidof( ID3D11Texture2D ), ( LPVOID * )&backBufferTexture ); if( FAILED( result ) ) { DXTRACE_MSG( "Failed to get the swap chain back buffer!" ); return false; } result = d3dDevice_->CreateRenderTargetView( backBufferTexture, 0, &backBufferTarget_ ); if( backBufferTexture ) { backBufferTexture->Release(); } if( FAILED ( result )) { DXTRACE_MSG( "Failed to create the render target view! "); return false; } d3dContext_->OMSetRenderTargets( 1, &backBufferTarget_, 0 ); //The creation and setting of a full-screen viewport D3D11_VIEWPORT viewport; viewport.Width = static_cast<float>( width ); viewport.Height = static_cast<float>( height ); viewport.MinDepth = 0.0f; viewport.MaxDepth = 1.0f; viewport.TopLeftX = 0.0f; viewport.TopLeftY = 0.0f; d3dContext_->RSSetViewports( 1, &viewport ); ZeroMemory( keyboardKeys_ , sizeof( keyboardKeys_ )); ZeroMemory( prevKeyboardKeys_ , sizeof( prevKeyboardKeys_ )); result = DirectInput8Create( hInstance_ , DIRECTINPUT_VERSION , IID_IDirectInput8 , ( void ** ) & directInput_ , 0 ); if( FAILED( result )) { return false; } result = directInput_ ->CreateDevice( GUID_SysKeyboard , &keyboardDevice_ , 0 ); if( FAILED( result )) { return false; } result = keyboardDevice_ ->SetDataFormat( &c_dfDIKeyboard ); if( FAILED( result )) { return false; } result = keyboardDevice_ ->SetCooperativeLevel( hwnd_ , DISCL_FOREGROUND | DISCL_NONEXCLUSIVE ); if( FAILED( result )) { return false; } result = keyboardDevice_ ->Acquire(); if( FAILED( result )) { return false; } mousePosX_ = mousePosY_ = mouseWheel_ = 0 ; result = directInput_ ->CreateDevice( GUID_SysMouse , &mouseDevice_ , 0 ); if( FAILED( result )) { return false; } result = mouseDevice_ ->SetDataFormat( &c_dfDIMouse ); if( FAILED( result )) { return false; } result = mouseDevice_ ->SetCooperativeLevel( hwnd_ , DISCL_FOREGROUND | DISCL_NONEXCLUSIVE ); if( FAILED( result )) { return false; } result = mouseDevice_ ->Acquire(); if( FAILED( result )) { return false; } return LoadContent(); }
// Simulates constructor delegation // HINSTANCE handle to an instance // HWND handle to a window bool Dx11DemoBase::Initialize(HINSTANCE hInstance, HWND hwnd) { hInstance_ = hInstance; // Save instance locally hwnd_ = hwnd; // Save window handle locally RECT dimensions; // Create rectagle object GetClientRect(hwnd, &dimensions); // Retrieves the coordinates of a window's client area unsigned int width = dimensions.right - dimensions.left; // Calc width of window area unsigned int height = dimensions.bottom - dimensions.top; // Calc length of window area // Enumeration of driver type options D3D_DRIVER_TYPE driverTypes[] = { D3D_DRIVER_TYPE_HARDWARE, D3D_DRIVER_TYPE_WARP, D3D_DRIVER_TYPE_REFERENCE, D3D_DRIVER_TYPE_SOFTWARE }; // Macro for returning the number of elements in the array unsigned int totalDriverTypes = ARRAYSIZE(driverTypes); // Enumeration of targeted features for D3D // Specifcally allowing the targeting of specific versions of D3D D3D_FEATURE_LEVEL featureLevels[] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0 }; // Macro for returning the number of elements in the array unsigned int totalFeatureLevels = ARRAYSIZE(featureLevels); // Allows for the creation of a buffer(s) // These buffers also have the ability to be swapped // Mutliple buffers have the potential to increase performance DXGI_SWAP_CHAIN_DESC swapChainDesc; ZeroMemory(&swapChainDesc, sizeof(swapChainDesc)); // Allocates memory and fills the block with 0s swapChainDesc.BufferCount = 1; // Number of buffers swapChainDesc.BufferDesc.Width = width; // Width of buffer swapChainDesc.BufferDesc.Height = height; // Height of buffer swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; // Determines the data format type (A four-component, 32-bit unsigned-normalized-integer format that supports 8 bits per channel including alpha) -- from docs swapChainDesc.BufferDesc.RefreshRate.Numerator = 60; // The refresh rate is how many times a second it draws the back buffer to the front buffer swapChainDesc.BufferDesc.RefreshRate.Denominator = 1; swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; // Use the surface or resource as an output render target swapChainDesc.OutputWindow = hwnd; // Supply the window handle for output swapChainDesc.Windowed = true; // Window mode YES swapChainDesc.SampleDesc.Count = 1; swapChainDesc.SampleDesc.Quality = 0; unsigned int creationFlags = 0; // Defines a debug flag that if set adds the D3D debug flag on the creation of D3D11CreateDeviceAndSwapChain #ifdef _DEBUG creationFlags |= D3D11_CREATE_DEVICE_DEBUG; #endif HRESULT result; // Gives detailed info about the return set specifically any information regarding errors or warnings unsigned int driver = 0; // Index for looping through driver types // Determine the Driver support level // Simultaneously create Swap Chain for given device for (driver = 0; driver < totalDriverTypes; ++driver) { result = D3D11CreateDeviceAndSwapChain( 0, driverTypes[driver], 0, creationFlags, featureLevels, totalFeatureLevels, D3D11_SDK_VERSION, &swapChainDesc, &swapChain_, &d3dDevice_, &featureLevel_, &d3dContext_ ); // Check if result was succesful if (SUCCEEDED(result)) { driverType_ = driverTypes[driver]; break; } } // All attempts failed to create D3D device. Exit now if (FAILED(result)) { wprintf(L"Failed to create the Direct3D device!"); // Print to stdout (L stands for long character) //DXTRACE_MSG( "Failed to create the Direct3D device!" ); return false; } ID3D11Texture2D* backBufferTexture; result = swapChain_->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&backBufferTexture); if (FAILED(result)) { wprintf(L"Failed to get the swap chain back buffer!"); // Print to stdout (L stands for long character) //DXTRACE_MSG( "Failed to get the swap chain back buffer!" ); return false; } // Creates a render view for accessing resource data result = d3dDevice_->CreateRenderTargetView(backBufferTexture, 0, &backBufferTarget_); if (backBufferTexture) backBufferTexture->Release(); // Deallocate a resource // Failed to create render view if (FAILED(result)) { wprintf(L"Failed to create the render target view!"); // Print to stdout (L stands for long character) //DXTRACE_MSG( "Failed to create the render target view!" ); return false; } // Bind one or more render targets atomically d3dContext_->OMSetRenderTargets(1, &backBufferTarget_, 0); // Allows for the definition of viewport dimensions D3D11_VIEWPORT viewport; viewport.Width = static_cast<float>(width); viewport.Height = static_cast<float>(height); viewport.MinDepth = 0.0f; viewport.MaxDepth = 1.0f; viewport.TopLeftX = 0.0f; viewport.TopLeftY = 0.0f; d3dContext_->RSSetViewports(1, &viewport); // Bind viewport to the rasterizer stage of the pipeline return LoadContent(); }
// // Initialise base DirectX // bool DirectXClass::Initialise(HWND hwnd, HINSTANCE hInstance) { HRESULT hr = 0; m_windowHandel = hwnd; RECT rc; GetClientRect(m_windowHandel, &rc); UINT width = rc.right - rc.left; UINT height = rc.bottom - rc.top; UINT createDeviceFlags = 0; #ifdef _DEBUG createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG; #endif D3D_FEATURE_LEVEL featureLevels[] = { D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0, D3D_FEATURE_LEVEL_9_3, D3D_FEATURE_LEVEL_9_2, D3D_FEATURE_LEVEL_9_1 }; D3D_FEATURE_LEVEL featureLevel; // // Describe and create swapchain // DXGI_SWAP_CHAIN_DESC swapChainDesc; ZeroMemory(&swapChainDesc, sizeof(DXGI_SWAP_CHAIN_DESC)); swapChainDesc.BufferCount = 1; swapChainDesc.BufferDesc.Width = width; swapChainDesc.BufferDesc.Height = height; swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swapChainDesc.OutputWindow = hwnd; swapChainDesc.SampleDesc.Count = 1; swapChainDesc.SampleDesc.Quality = 0; swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; swapChainDesc.Windowed = TRUE; hr = D3D11CreateDeviceAndSwapChain(nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr, createDeviceFlags, featureLevels, _countof(featureLevels), D3D11_SDK_VERSION, &swapChainDesc, &m_SwapChain, &m_3dDevice, &featureLevel, &m_3dDeviceContext); if (hr == E_FAIL) { hr = D3D11CreateDeviceAndSwapChain(nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr, createDeviceFlags, &featureLevels[1], _countof(featureLevels) - 1, D3D11_SDK_VERSION, &swapChainDesc, &m_SwapChain, &m_3dDevice, &featureLevel, &m_3dDeviceContext); } if (FAILED(hr)) return false; // // Create back buffer // ID3D11Texture2D* backBuffer; hr = m_SwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&backBuffer); if (FAILED(hr)) return false; hr = m_3dDevice->CreateRenderTargetView(backBuffer, nullptr, &m_RenderTarget); if (FAILED(hr)) return false; backBuffer->Release(); // // Create the depth buffer // D3D11_TEXTURE2D_DESC depthBufferDesc; ZeroMemory(&depthBufferDesc, sizeof(D3D11_TEXTURE2D_DESC)); depthBufferDesc.ArraySize = 1; depthBufferDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL; depthBufferDesc.CPUAccessFlags = 0; // No CPU access required. depthBufferDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; depthBufferDesc.Width = width; depthBufferDesc.Height = height; depthBufferDesc.MipLevels = 1; depthBufferDesc.SampleDesc.Count = 1; depthBufferDesc.SampleDesc.Quality = 0; depthBufferDesc.Usage = D3D11_USAGE_DEFAULT; hr = m_3dDevice->CreateTexture2D(&depthBufferDesc, nullptr, &m_DepthStencilBuffer); if (FAILED(hr)) return false; hr = m_3dDevice->CreateDepthStencilView(m_DepthStencilBuffer, nullptr, &m_DepthStencil); if (FAILED(hr)) return false; D3D11_DEPTH_STENCIL_DESC depthStencilState; ZeroMemory(&depthStencilState, sizeof(D3D11_DEPTH_STENCIL_DESC)); depthStencilState.DepthEnable = TRUE; depthStencilState.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL; depthStencilState.DepthFunc = D3D11_COMPARISON_LESS; depthStencilState.StencilEnable = FALSE; hr = m_3dDevice->CreateDepthStencilState(&depthStencilState, &m_DepthStencilState); // // Setup rasterizer state. // D3D11_RASTERIZER_DESC rasterizerDesc; ZeroMemory(&rasterizerDesc, sizeof(D3D11_RASTERIZER_DESC)); rasterizerDesc.AntialiasedLineEnable = FALSE; rasterizerDesc.CullMode = D3D11_CULL_NONE; rasterizerDesc.DepthBias = 0; rasterizerDesc.DepthBiasClamp = 0.0f; rasterizerDesc.DepthClipEnable = TRUE; rasterizerDesc.FillMode = D3D11_FILL_WIREFRAME; rasterizerDesc.FrontCounterClockwise = FALSE; rasterizerDesc.MultisampleEnable = FALSE; rasterizerDesc.ScissorEnable = FALSE; rasterizerDesc.SlopeScaledDepthBias = 0.0f; hr = m_3dDevice->CreateRasterizerState(&rasterizerDesc, &m_RasterizerState); if (FAILED(hr)) return false; // // Initialize the viewport to occupy the entire client area. // m_Viewport.Width = static_cast<float>(width); m_Viewport.Height = static_cast<float>(height); m_Viewport.TopLeftX = 0.0f; m_Viewport.TopLeftY = 0.0f; m_Viewport.MinDepth = 0.0f; m_Viewport.MaxDepth = 1.0f; return LoadContent(); }
bool DemoBase::Initialize(HINSTANCE hInstance, HWND hwnd) { hInstance_ = hInstance; hwnd_ = hwnd; RECT dimensions; GetClientRect(hwnd, &dimensions); unsigned int width = dimensions.right - dimensions.left; unsigned int height = dimensions.bottom - dimensions.top; D3D_DRIVER_TYPE driverTypes[] = { D3D_DRIVER_TYPE_HARDWARE, D3D_DRIVER_TYPE_WARP, D3D_DRIVER_TYPE_SOFTWARE }; unsigned int totalDriverTypes = ARRAYSIZE( driverTypes ); D3D_FEATURE_LEVEL featureLevels[] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0 }; unsigned int totalFeatureLevels = ARRAYSIZE(featureLevels); DXGI_SWAP_CHAIN_DESC swapChainDesc; ZeroMemory(&swapChainDesc, sizeof(swapChainDesc)); swapChainDesc.BufferCount = 1; swapChainDesc.BufferDesc.Width = width; swapChainDesc.BufferDesc.Height = height; swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; swapChainDesc.BufferDesc.RefreshRate.Numerator = 60; swapChainDesc.BufferDesc.RefreshRate.Denominator = 1; swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swapChainDesc.OutputWindow = hwnd; swapChainDesc.Windowed = true; swapChainDesc.SampleDesc.Count = 1; swapChainDesc.SampleDesc.Quality = 0; unsigned int creationFlags = 0; #ifdef _DEBUG creationFlags |= D3D11_CREATE_DEVICE_DEBUG; #endif HRESULT result; unsigned int driver = 0; for (; driver < totalDriverTypes; ++driver) { result = D3D11CreateDeviceAndSwapChain(0, driverTypes[driver], 0, creationFlags, featureLevels, totalFeatureLevels, D3D11_SDK_VERSION, &swapChainDesc, &swapChain_, &d3dDevice_, &featureLevel_, &d3dContext_); if (SUCCEEDED(result)) { driverType_ = driverTypes[driver]; break; } } if (FAILED(result)) { DXTRACE_MSG(L"Failed to create the Direct3D device!"); return false; } ID3D11Texture2D* backBufferTexture; result = swapChain_->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&backBufferTexture); if (FAILED(result)) { DXTRACE_MSG(L"Failed to get the swap chain back buffer!"); return false; } result = d3dDevice_->CreateRenderTargetView(backBufferTexture, 0, &backBufferTarget_); if (backBufferTexture) backBufferTexture->Release(); if (FAILED(result)) { DXTRACE_MSG(L"Failed to create the render target view!"); return false; } d3dContext_->OMSetRenderTargets(1, &backBufferTarget_, 0); D3D11_VIEWPORT viewport; viewport.Width = static_cast<float>(width); viewport.Height = static_cast<float>(height); viewport.MinDepth = 0.0f; viewport.MaxDepth = 1.0f; viewport.TopLeftX = 0.0f; viewport.TopLeftY = 0.0f; d3dContext_->RSSetViewports(1, &viewport); return LoadContent(); }
//初始化 bool Dx11DemoBase::Initialize( HINSTANCE hInstance , HWND hwnd ) { hInstance_ = hInstance; hwnd_ = hwnd; RECT dimensions;//创建矩形对象 //获取窗口客户区 GetClientRect( hwnd , &dimensions ); unsigned int width = dimensions.right - dimensions.left; unsigned int height = dimensions.bottom - dimensions.top; D3D_DRIVER_TYPE driverTypes[] = { D3D_DRIVER_TYPE_HARDWARE, D3D_DRIVER_TYPE_WARP, D3D_DRIVER_TYPE_SOFTWARE }; unsigned int totalDriverTypes = ARRAYSIZE( driverTypes ); D3D_FEATURE_LEVEL featureLevels[] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0 }; unsigned int totalFeatureLevels = ARRAYSIZE( featureLevels ); DXGI_SWAP_CHAIN_DESC swapChainDesc; ZeroMemory( &swapChainDesc , sizeof( swapChainDesc )); swapChainDesc.BufferCount = 1; swapChainDesc.BufferDesc.Width = width; swapChainDesc.BufferDesc.Height = height; swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;//specfic the Format swapChainDesc.BufferDesc.RefreshRate.Numerator = 60; swapChainDesc.BufferDesc.RefreshRate.Denominator = 1; swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swapChainDesc.OutputWindow = hwnd; swapChainDesc.Windowed = true; swapChainDesc.SampleDesc.Count = 1; swapChainDesc.SampleDesc.Quality = 0; unsigned int creationFlags = 0; //Create the DirectX 11 device,context,swapchain #ifdef _DEBUG creationFlags |= D3D11_CREATE_DEVICE_DEBUG; #endif HRESULT result; unsigned int driver = 0 ; for( driver = 0; driver < totalDriverTypes; ++driver ) { result = D3D11CreateDeviceAndSwapChain( 0, driverTypes[driver], 0, creationFlags, featureLevels, totalFeatureLevels, D3D11_SDK_VERSION, &swapChainDesc, &swapChain_, &d3dDevice_, &featureLevel_, &d3dContext_ ); if( SUCCEEDED( result ) ) { driverType_ = driverTypes[ driver ]; break; } } if( FAILED( result )) { DXTRACE_MSG( "Failed to create the Direct3D device!" ); return false; } //Render TargetView Creation ID3D11Texture2D * backBufferTexture; result = swapChain_->GetBuffer( 0, __uuidof( ID3D11Texture2D ), ( LPVOID * )&backBufferTexture ); if( FAILED( result ) ) { DXTRACE_MSG( "Failed to get the swap chain back buffer!" ); return false; } result = d3dDevice_->CreateRenderTargetView( backBufferTexture, 0, &backBufferTarget_ ); if( backBufferTexture ) { backBufferTexture->Release(); } if( FAILED ( result )) { DXTRACE_MSG( "Failed to create the render target view! "); return false; } //Create the texture2d desc D3D11_TEXTURE2D_DESC depthTexDesc; ZeroMemory( &depthTexDesc , sizeof( depthTexDesc )); depthTexDesc.Width = width; depthTexDesc.Height = height; depthTexDesc.MipLevels = 1; depthTexDesc.ArraySize = 1; depthTexDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; depthTexDesc.SampleDesc.Count = 1; depthTexDesc.SampleDesc.Quality = 0; depthTexDesc.Usage = D3D11_USAGE_DEFAULT; depthTexDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL; depthTexDesc.CPUAccessFlags = 0; depthTexDesc.MiscFlags = 0; result = d3dDevice_ ->CreateTexture2D( &depthTexDesc , NULL , &depthTexture_ ); if( FAILED( result )) { DXTRACE_MSG( "Failed to create the depth texture!" ); return false; } //Create the depth stencil view D3D11_DEPTH_STENCIL_VIEW_DESC descDSV; ZeroMemory( &descDSV , sizeof( descDSV )); descDSV.Format = depthTexDesc.Format; descDSV.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D; descDSV.Texture2D.MipSlice = 0; result = d3dDevice_ ->CreateDepthStencilView( depthTexture_ , &descDSV , &depthStencilView_ ); if( FAILED( result )) { DXTRACE_MSG( "Failed to create the depth stencil view!" ); return false; } d3dContext_->OMSetRenderTargets( 1, &backBufferTarget_, depthStencilView_ ); //The creation and setting of a full-screen viewport D3D11_VIEWPORT viewport; viewport.Width = static_cast<float>( width ); viewport.Height = static_cast<float>( height ); viewport.MinDepth = 0.0f; viewport.MaxDepth = 1.0f; viewport.TopLeftX = 0.0f; viewport.TopLeftY = 0.0f; d3dContext_->RSSetViewports( 1, &viewport ); return LoadContent(); }