// Loads and initializes application assets when the application is loaded.
DWriteOpenTypeEnumerationMain::DWriteOpenTypeEnumerationMain(const std::shared_ptr<DX::DeviceResources>& deviceResources) :
    m_deviceResources(deviceResources)
{
    // Register to be notified if the device is lost or recreated.
    m_deviceResources->RegisterDeviceNotify(this);

    m_sceneRenderer = std::unique_ptr<DWriteOpenTypeEnumerationRenderer>(new DWriteOpenTypeEnumerationRenderer(m_deviceResources));

    // Create variables to store the font family and index in the collection
    Microsoft::WRL::ComPtr<IDWriteFontFamily> tempFontFamily;
    Microsoft::WRL::ComPtr<IDWriteFont> tempFont;
    Microsoft::WRL::ComPtr<IDWriteFontFace> tempFontFace;
    Microsoft::WRL::ComPtr<IDWriteFontCollection> fontCollection;
    Microsoft::WRL::ComPtr<IDWriteTextAnalyzer> textAnalyzer;

    UINT32 fontIndex = 0;
    BOOL isPresent = false;

    // Get a copy of the system font collection
    m_deviceResources->GetDWriteFactory()->GetSystemFontCollection(&fontCollection);

    WCHAR* fontFaceNames[] = {L"Arial", L"Times New Roman", L"Meiryo", L"Gabriola"};
    Microsoft::WRL::ComPtr<IDWriteFontFace2>* fontFaces[4] = {&m_arial, &m_times, &m_meiryo, &m_gabriola};

    for (int i = 0; i < ARRAYSIZE(fontFaceNames); i++)
    {
        fontCollection->FindFamilyName(fontFaceNames[i], &fontIndex, &isPresent);
        if (isPresent)
        {
            DX::ThrowIfFailed(
                fontCollection->GetFontFamily(fontIndex, &tempFontFamily)
                );

            DX::ThrowIfFailed(
                tempFontFamily->GetFirstMatchingFont(
                    DWRITE_FONT_WEIGHT_NORMAL,
                    DWRITE_FONT_STRETCH_NORMAL,
                    DWRITE_FONT_STYLE_NORMAL,
                    &tempFont
                    )
                );

            DX::ThrowIfFailed(
                tempFont->CreateFontFace(&tempFontFace)
                );

            DX::ThrowIfFailed(
                tempFontFace.As(fontFaces[i])
                );
        }
    }

    // Create the IDWriteTextAnalyzer that we'll need to get OpenType feature coverage from
    m_deviceResources->GetDWriteFactory()->CreateTextAnalyzer(&textAnalyzer);

    textAnalyzer.As(&m_textAnalyzer);
}
Esempio n. 2
0
void Renderer::CreateSwapChain()
{
	DXGI_SWAP_CHAIN_DESC1 SwapChainDesc = {};
	SwapChainDesc.BufferCount = BufferFrameCount;
	SwapChainDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
	SwapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
	SwapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
	SwapChainDesc.SampleDesc.Count = 1;

	Window::WindowSize Size = TargetWindow.GetWindowSize();
	SwapChainDesc.Width = Size.first;
	SwapChainDesc.Height = Size.second;

	Microsoft::WRL::ComPtr<IDXGISwapChain1> HelperSwapChain;
	Utility::ThrowOnFail(DeviceContext.GetFactory()->CreateSwapChainForHwnd(DeviceContext.GetCommandQueue().Get(), TargetWindow.GetHandle(), &SwapChainDesc, nullptr, nullptr, &HelperSwapChain));

	Utility::ThrowOnFail(HelperSwapChain.As(&SwapChain));
	BufferFrameIndex = SwapChain->GetCurrentBackBufferIndex();
}
	void Load(ID3D11ShaderResourceView* texture)
	{
		mTexture = texture;

		if (texture)
		{
			Microsoft::WRL::ComPtr<ID3D11Resource> resource;
			texture->GetResource(resource.GetAddressOf());

			D3D11_RESOURCE_DIMENSION dim;
			resource->GetType(&dim);

			if (dim != D3D11_RESOURCE_DIMENSION_TEXTURE2D)
				throw std::exception("ScrollingBackground expects a Texture2D");

			Microsoft::WRL::ComPtr<ID3D11Texture2D> tex2D;
			resource.As(&tex2D);

			D3D11_TEXTURE2D_DESC desc;
			tex2D->GetDesc(&desc);

			mTextureWidth = desc.Width;
			mTextureHeight = desc.Height;

			mTextureSize.x = float(desc.Width);
			mTextureSize.y = float( desc.Height );
			mTextureSize.y = 0.f; //Wrong - loss of usefull data
		//	mOrigin.y = desc.Width / 2.f;
		//	mOrigin.x = desc.Width / 2.f;
			mOrigin.x = 0.f;
			mOrigin.y = 0.f;
			
			
			TempPlayerPos.x = 0;
			TempPlayerPos.y = 0;
			
		}
	}
DWRITE_TEXT_METRICS TextFormatD2D::GetMetrics(
	const WCHAR* str, UINT strLen, bool gdiEmulation, float maxWidth)
{
	// GDI+ compatibility: If the last character is a newline, GDI+ measurements seem to ignore it.
	bool strippedLastNewLine = false;
	if (strLen > 2 && str[strLen - 1] == L'\n')
	{
		strippedLastNewLine = true;
		--strLen;

		if (str[strLen - 1] == L'\r')
		{
			--strLen;
		}
	}

	DWRITE_TEXT_METRICS metrics = {0};
	Microsoft::WRL::ComPtr<IDWriteTextLayout> textLayout;
	HRESULT hr = CanvasD2D::c_DWFactory->CreateTextLayout(
		str,
		strLen,
		m_TextFormat.Get(),
		maxWidth,
		10000,
		textLayout.GetAddressOf());
	if (SUCCEEDED(hr))
	{
		const float xOffset = m_TextFormat->GetFontSize() / 6.0f;
		if (gdiEmulation)
		{
			Microsoft::WRL::ComPtr<IDWriteTextLayout1> textLayout1;
			textLayout.As(&textLayout1);

			const float emOffset = xOffset / 24.0f;
			const DWRITE_TEXT_RANGE range = {0, strLen};
			textLayout1->SetCharacterSpacing(emOffset, emOffset, 0.0f, range);
		}

		textLayout->GetMetrics(&metrics);
		if (metrics.width > 0.0f)
		{
			if (gdiEmulation)
			{
				metrics.width += xOffset * 2;
				metrics.height += m_ExtraHeight;

				// GDI+ compatibility: If the string contains a newline (even if it is the
				// stripped last character), GDI+ adds the line gap to the overall height.
				if (strippedLastNewLine || wmemchr(str, L'\n', strLen) != nullptr)
				{
					metrics.height += m_LineGap;
				}
			}
			else
			{
				// GDI+ compatibility: With accurate metrics, the line gap needs to be subtracted
				// from the overall height if the string does not contain newlines.
				if (!strippedLastNewLine && wmemchr(str, L'\n', strLen) == nullptr)
				{
					metrics.height -= m_LineGap;
				}
			}
		}
		else
		{
			// GDI+ compatibility: Get rid of the height that DirectWrite assigns to zero-width
			// strings.
			metrics.height = 0.0f;
		}
	}

	return metrics;
}
void Sample3DSceneRenderer::Render()
{
	// Loading is asynchronous. Only draw geometry after it's loaded.
	//if (!m_loadingComplete)
	//{
	//	return;
	//}

	auto context = m_deviceResources->GetD3DDeviceContext();

	// Set render targets to the screen.
	ID3D11RenderTargetView *const targets[1] = { m_deviceResources->GetBackBufferRenderTargetView() };
	context->OMSetRenderTargets(1, targets, m_deviceResources->GetDepthStencilView());

	D3D11_TEXTURE2D_DESC pDesc;
	Microsoft::WRL::ComPtr<ID3D11Resource> res;
	//1.) -----------------
	//m_texture->GetResource(&res);
	//((ID3D11Texture2D*)res.Get())->GetDesc(&pDesc); // Usually dangerous!

	//2.) -----------------
	m_texture->GetResource(res.GetAddressOf());
	Microsoft::WRL::ComPtr<ID3D11Texture2D> text2D;
	res.As(&text2D);
	text2D->GetDesc(&pDesc);

	auto height = pDesc.Height; //texture height
	auto width = pDesc.Width; //texture width

	auto windowSize = m_deviceResources->GetOutputSize(); // physical screen resolution
	auto logicalSize = m_deviceResources->GetLogicalSize(); //DPI dependent resolution

															// Draw sprites
	m_sprites->Begin();

	background->Draw(m_sprites.get());
	clouds->Draw(m_sprites.get());
	
	//Drawing walls

	for (auto& wall : wallsVector)
	{
		wall.Draw(m_sprites.get());
	}

	//wall->Draw(m_sprites.get());
	//wall2->Draw(m_sprites.get());


	player->Draw(m_sprites.get());
	//ship->draw(m_sprites.get());

	for (auto& enemy : enemiesVector)
	{
		enemy.Draw(m_sprites.get());

	}


	clouds2->Draw(m_sprites.get());

	m_font->DrawString(m_sprites.get(), collisionString.c_str(), XMFLOAT2(100, 10), Colors::Yellow);
	m_sprites->End();


}
Esempio n. 6
0
void QtTestGui::resizeEvent(QResizeEvent *e){
	HRESULT hr = S_OK;

	uint32_t width = static_cast<uint32_t>((std::max)(this->width(), 1));
	uint32_t height = static_cast<uint32_t>((std::max)(this->height(), 1));
	std::lock_guard<std::mutex> lk(this->d3dMtx);

	this->d3dRtView = nullptr;

	if (!this->d3dSwapChain){
		Microsoft::WRL::ComPtr<IDXGIDevice2> dxgiDevice;
		Microsoft::WRL::ComPtr<IDXGIAdapter> dxgiAdapter;
		Microsoft::WRL::ComPtr<IDXGIFactory2> dxgiFactory;
		Microsoft::WRL::ComPtr<IDXGISwapChain1> swapChainTmp;

		hr = this->d3dDev.As(&dxgiDevice);
		hr = dxgiDevice->GetParent(IID_PPV_ARGS(dxgiAdapter.GetAddressOf()));
		hr = dxgiAdapter->GetParent(IID_PPV_ARGS(dxgiFactory.GetAddressOf()));

		HWND hwnd = reinterpret_cast<HWND>(this->winId());
		HWND hwnd2 = reinterpret_cast<HWND>(this->effectiveWinId());
		DXGI_SWAP_CHAIN_DESC1 swapChainDesc;
		DXGI_SWAP_CHAIN_FULLSCREEN_DESC fullscreenDesc;

		swapChainDesc.Width = width;
		swapChainDesc.Height = height;
		swapChainDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
		swapChainDesc.Stereo = FALSE;
		swapChainDesc.SampleDesc.Count = 1;
		swapChainDesc.SampleDesc.Quality = 0;
		swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
		swapChainDesc.BufferCount = 2;
		swapChainDesc.Scaling = DXGI_SCALING::DXGI_SCALING_STRETCH;
		swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT::DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL;// DXGI_SWAP_EFFECT::DXGI_SWAP_EFFECT_SEQUENTIAL;
		swapChainDesc.AlphaMode = DXGI_ALPHA_MODE::DXGI_ALPHA_MODE_IGNORE;
		swapChainDesc.Flags = 0;

		fullscreenDesc.RefreshRate.Numerator = 0;
		fullscreenDesc.RefreshRate.Denominator = 0;
		fullscreenDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER::DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
		fullscreenDesc.Scaling = DXGI_MODE_SCALING::DXGI_MODE_SCALING_CENTERED;
		fullscreenDesc.Windowed = TRUE;

		hr = dxgiFactory->CreateSwapChainForHwnd(this->d3dDev.Get(), hwnd, &swapChainDesc, &fullscreenDesc, nullptr, swapChainTmp.GetAddressOf());
		hr = swapChainTmp.As(&this->d3dSwapChain);
	}
	else{
		hr = this->d3dSwapChain->ResizeBuffers(2, width, height, DXGI_FORMAT_R8G8B8A8_UNORM, 0);
	}

	Microsoft::WRL::ComPtr<IDXGISurface> dxgiSurface;
	Microsoft::WRL::ComPtr<ID3D11Texture2D> d3dTex;

	hr = this->d3dSwapChain->GetBuffer(0, IID_PPV_ARGS(dxgiSurface.GetAddressOf()));
	hr = dxgiSurface.As(&d3dTex);

	D3D11_TEXTURE2D_DESC tex2dDec;
	D3D11_RENDER_TARGET_VIEW_DESC d3dRtDesc;

	d3dTex->GetDesc(&tex2dDec);

	d3dRtDesc.ViewDimension = D3D11_RTV_DIMENSION::D3D11_RTV_DIMENSION_TEXTURE2D;
	d3dRtDesc.Format = tex2dDec.Format;
	d3dRtDesc.Texture2D.MipSlice = 0;

	this->d3dDev->CreateRenderTargetView(d3dTex.Get(), &d3dRtDesc, this->d3dRtView.ReleaseAndGetAddressOf());

	D3D11_VIEWPORT viewPort;

	viewPort.TopLeftX = viewPort.TopLeftY = 0.0f;
	viewPort.Width = static_cast<float>(width);
	viewPort.Height = static_cast<float>(height);
	viewPort.MinDepth = 0.0f;
	viewPort.MaxDepth = 1.0f;

	this->d3dCtx->RSSetViewports(1, &viewPort);

	this->UpdateProjection();
}
Esempio n. 7
0
void DirectXPanelBase::CreateDeviceResources()
{
    // This flag adds support for surfaces with a different color channel ordering than the API default.
    // It is recommended usage, and is required for compatibility with Direct2D.
    UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;

#if defined(_DEBUG)
    // If the project is in a debug build, enable debugging via SDK Layers with this flag.
    creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif

    // This array defines the set of DirectX hardware feature levels this app will support.
    // Note the ordering should be preserved.
    // Don't forget to declare your application's minimum required feature level in its
    // description.  All applications are assumed to support 9.1 unless otherwise stated.
    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
    };

    // Create the DX11 API device object, and get a corresponding context.
    Microsoft::WRL::ComPtr<ID3D11Device> device;
    Microsoft::WRL::ComPtr<ID3D11DeviceContext> context;
    DX::ThrowIfFailed(
        D3D11CreateDevice(
            nullptr,                    // Specify null to use the default adapter.
            D3D_DRIVER_TYPE_HARDWARE,
            0,
            creationFlags,              // Optionally set debug and Direct2D compatibility flags.
            featureLevels,              // List of feature levels this app can support.
            ARRAYSIZE(featureLevels),
            D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Windows Store apps.
            &device,                    // Returns the Direct3D device created.
            NULL,                       // Returns feature level of device created.
            &context                    // Returns the device immediate context.
        )
    );

    // Get D3D11.1 device
    DX::ThrowIfFailed(
        device.As(&m_d3dDevice)
    );

    // Get D3D11.1 context
    DX::ThrowIfFailed(
        context.As(&m_d3dContext)
    );

    // Get underlying DXGI device of D3D device
    Microsoft::WRL::ComPtr<IDXGIDevice> dxgiDevice;
    DX::ThrowIfFailed(
        m_d3dDevice.As(&dxgiDevice)
    );

    // Get D2D device
    DX::ThrowIfFailed(
        m_d2dFactory->CreateDevice(dxgiDevice.Get(), &m_d2dDevice)
    );

    // Get D2D context
    DX::ThrowIfFailed(
        m_d2dDevice->CreateDeviceContext(
            D2D1_DEVICE_CONTEXT_OPTIONS_NONE,
            &m_d2dContext
        )
    );

    // Set D2D text anti-alias mode to Grayscale to ensure proper rendering of text on intermediate surfaces.
    m_d2dContext->SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE);
}
Esempio n. 8
0
void DirectXPanelBase::CreateSizeDependentResources()
{
    bool setSwapChain = false;

    // Ensure dependent objects have been released.
    ReleaseSizeDependentResources();
    
    // If the swap chain already exists, then resize it.
    if (m_swapChain != nullptr)
    {
        // If the swap chain already exists, resize it.
        HRESULT hr = m_swapChain->ResizeBuffers(
            2, // Double-buffered swap chain.
            static_cast<UINT>((float) max(m_width * m_compositionScaleX, 1)),
            static_cast<UINT>((float) max(m_height * m_compositionScaleY, 1)),
            DXGI_FORMAT_B8G8R8A8_UNORM,
            0
        );

        if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET)
        {
            // If the device was removed for any reason, a new device and swap chain will need to be created.
            HandleDeviceLost();

            // Everything is set up now. Do not continue execution of this method. 
            return;
        }
        else
        {
            DX::ThrowIfFailed(hr);
        }
    }
    else // Otherwise, create a new one.
    {
        DXGI_SWAP_CHAIN_DESC1 swapChainDesc = { 0 };
        swapChainDesc.Width = static_cast<UINT>((float) max(m_width * m_compositionScaleX, 1));      // Match the size of the panel.
        swapChainDesc.Height = static_cast<UINT>((float) max(m_height * m_compositionScaleY, 1));
        swapChainDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;                  // This is the most common swap chain format.
        swapChainDesc.Stereo = false;
        swapChainDesc.SampleDesc.Count = 1;                                 // Don't use multi-sampling.
        swapChainDesc.SampleDesc.Quality = 0;
        swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
        swapChainDesc.BufferCount = 2;                                      // Use double buffering to enable flip.
        swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL;        // All Windows Store apps must use this SwapEffect.
        swapChainDesc.Flags = 0;
        swapChainDesc.AlphaMode = m_alphaMode;

        // Get underlying DXGI Device from D3D Device.
        Microsoft::WRL::ComPtr<IDXGIDevice1> dxgiDevice;
        DX::ThrowIfFailed(
            m_d3dDevice.As(&dxgiDevice)
        );

        // Get adapter.
        Microsoft::WRL::ComPtr<IDXGIAdapter> dxgiAdapter;
        DX::ThrowIfFailed(
            dxgiDevice->GetAdapter(&dxgiAdapter)
        );

        // Get factory.
        Microsoft::WRL::ComPtr<IDXGIFactory2> dxgiFactory;
        DX::ThrowIfFailed(
            dxgiAdapter->GetParent(IID_PPV_ARGS(&dxgiFactory))
        );

        Microsoft::WRL::ComPtr<IDXGISwapChain1> swapChain;
        // Create swap chain.
        DX::ThrowIfFailed(
            dxgiFactory->CreateSwapChainForComposition(
                m_d3dDevice.Get(),
                &swapChainDesc,
                nullptr,
                &swapChain
            )
        );
        swapChain.As(&m_swapChain);

        // Ensure that DXGI does not queue more than one frame at a time. This both reduces 
        // latency and ensures that the application will only render after each VSync, minimizing 
        // power consumption.
        DX::ThrowIfFailed(
            dxgiDevice->SetMaximumFrameLatency(1)
        );

        setSwapChain = true;
    }

    // Ensure the physical pixel size of the swap chain takes into account both the XAML SwapChainPanel's logical layout size and 
    // any cumulative composition scale applied due to zooming, render transforms, or the system's current scaling plateau.
    // For example, if a 100x100 SwapChainPanel has a cumulative 2x scale transform applied, we instead create a 200x200 swap chain 
    // to avoid artifacts from scaling it up by 2x, then apply an inverse 1/2x transform to the swap chain to cancel out the 2x transform.
    DXGI_MATRIX_3X2_F inverseScale = { 0 };
    inverseScale._11 = 1.0f / m_compositionScaleX;
    inverseScale._22 = 1.0f / m_compositionScaleY;

    m_swapChain->SetMatrixTransform(&inverseScale);

    D2D1_BITMAP_PROPERTIES1 bitmapProperties =
        D2D1::BitmapProperties1(
            D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW,
            D2D1::PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
            s_dipsPerInch * m_compositionScaleX,
            s_dipsPerInch * m_compositionScaleY
    );

    // Direct2D needs the DXGI version of the backbuffer surface pointer.
    Microsoft::WRL::ComPtr<IDXGISurface> dxgiBackBuffer;
    DX::ThrowIfFailed(
        m_swapChain->GetBuffer(0, IID_PPV_ARGS(&dxgiBackBuffer))
    );

    // Get a D2D surface from the DXGI back buffer to use as the D2D render target.
    DX::ThrowIfFailed(
        m_d2dContext->CreateBitmapFromDxgiSurface(
            dxgiBackBuffer.Get(),
            &bitmapProperties,
            &m_d2dTargetBitmap
        )
    );

    m_d2dContext->SetDpi(s_dipsPerInch * m_compositionScaleX, s_dipsPerInch * m_compositionScaleY);
    m_d2dContext->SetTarget(m_d2dTargetBitmap.Get());

    if (setSwapChain)
    {
        SetSwapChain();
    }
}