void TextureWave::LoadTexture() { auto hr = CreateDDSTextureFromFile(m_d3dDevice, L"Texture/grass.dds", nullptr, &m_landGrassTexture); hr = CreateDDSTextureFromFile(m_d3dDevice, L"Texture/flare.dds", nullptr, &m_flameTexture); hr = CreateDDSTextureFromFile(m_d3dDevice, L"Texture/water2.dds", nullptr, &m_waveTexture); hr = CreateDDSTextureFromFile(m_d3dDevice, L"Texture/WireFence.dds", nullptr, &m_boxTexture); D3DHelper::ThrowIfFailed(hr); D3D11_SAMPLER_DESC sampleDesc; ZeroMemory(&sampleDesc, sizeof(D3D11_SAMPLER_DESC)); sampleDesc.Filter = D3D11_FILTER_ANISOTROPIC; sampleDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; sampleDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; sampleDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; sampleDesc.MipLODBias = 0.0f; sampleDesc.MaxAnisotropy = 4; sampleDesc.ComparisonFunc = D3D11_COMPARISON_NEVER; sampleDesc.BorderColor[0] = 0; sampleDesc.BorderColor[1] = 0; sampleDesc.BorderColor[2] = 0; sampleDesc.BorderColor[3] = 0; sampleDesc.MinLOD = 0.0f; sampleDesc.MaxLOD = D3D11_FLOAT32_MAX; D3DHelper::ThrowIfFailed(m_d3dDevice->CreateSamplerState(&sampleDesc, &m_samplerState)); m_currentRenderState = m_renderStateManager->GetSolidRenderState(); }
void CAnimationComponent::LoadTexture(string _textureName, RENDER_NODE_INFO* _rnInfo) { #ifndef IARESERVER CRenderer* renderer = CGame::GetInstance()->GetRenderer(); // complete the path to the file string texPath("Assets/Textures/"); texPath += _textureName; texPath += ".dds"; // transform the string to a wstring wstring wTexPath = wstring(texPath.begin(), texPath.end()); // load texture HRESULT hr = CreateDDSTextureFromFile(renderer->GetDevice(), wTexPath.c_str(), &_rnInfo->diffuseTex, &_rnInfo->diffuseTexSRV); // If the path didn't point to a file, load NotFound.dds to give a visual cue if (hr == BAD_PATH || hr == FILE_NOT_FOUND) { hr = 0; wTexPath = wstring(L"Assets/Textures/NotFound.dds"); hr = CreateDDSTextureFromFile(renderer->GetDevice(), wTexPath.c_str(), &_rnInfo->diffuseTex, &_rnInfo->diffuseTexSRV); } assert(!FAILED(hr) && "CRenderDataManager::LoadTexture() - Failed to load texture."); #endif }
bool D3DTextureDemo::Init() { if (!D3DApp::Init()) return false; mWaves.Init(160, 160, 1.0f, 0.03f, 3.25f, 0.4f); BuildLandGemetryBuffers(); BuildWaveGemetryBuffers(); LoadShader(); BuildVertexLayout(); BuildRasterState(); mCBObject.Initilize(m_d3dDevice); mCBLightingObject.Initilize(m_d3dDevice); //HR(D3DX11CreateShaderResourceViewFromFile( HR(CreateDDSTextureFromFile( m_d3dDevice, L"Texture/grass.dds", 0, &mGrassMapSRV, 0, nullptr), L"Create DDS grass texture"); HR(CreateDDSTextureFromFile( m_d3dDevice, L"Texture/water2.dds", 0, &mWavesMapSRV, 0, nullptr), L"Create DDS wave texture"); return true; }
void Cube::init_texture(ID3D11Device *pD3D11Device) { HRESULT hr; hr = CreateDDSTextureFromFile(pD3D11Device, L"../../media/textures/stone01.dds", NULL, &m_pTextures[0]); //DebugHR(hr); hr = CreateDDSTextureFromFile(pD3D11Device, L"../../media/textures/bump01.dds", NULL, &m_pTextures[1]); //DebugHR(hr); // Create a texture sampler state description. D3D11_SAMPLER_DESC samplerDesc; samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.MipLODBias = 0.0f; samplerDesc.MaxAnisotropy = 1; samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS; samplerDesc.BorderColor[0] = 0; samplerDesc.BorderColor[1] = 0; samplerDesc.BorderColor[2] = 0; samplerDesc.BorderColor[3] = 0; samplerDesc.MinLOD = 0; samplerDesc.MaxLOD = D3D11_FLOAT32_MAX; // Create the texture sampler state. hr = pD3D11Device->CreateSamplerState(&samplerDesc, &m_pTexSamplerState); //DebugHR(hr); }
void DEMO::Load() { heli.CreateGameObject(pDevice, "asset/heli.obj", Cube_VS, sizeof(Cube_VS)); skybox.CreateGameObject(pDevice, "asset/skybox.obj", SkyBox_VS, sizeof(SkyBox_VS)); ground.CreateGameObject(pDevice, "asset/Ground.obj", Cube_VS, sizeof(Cube_VS)); parkLight.CreateGameObject(pDevice, "asset/ParkLight.obj", Cube_VS, sizeof(Cube_VS)); CreateDDSTextureFromFile(pDevice, L"asset/Ground_norm.dds", NULL, &pGroundNormalMap); CreateDDSTextureFromFile(pDevice, L"asset/numbers_test1.dds", NULL, &pCubeShaderResourceView); CreateDDSTextureFromFile(pDevice, L"asset/SunsetSkybox.dds", NULL, &pSkyboxSunset); }
bool Texture::CreateFromFIle( const wchar_t* FileName, bool sRGB ) { if (m_hCpuDescriptorHandle.ptr == ~0ull) m_hCpuDescriptorHandle = Graphics::g_pCSUDescriptorHeap->Append().GetCPUHandle(); HRESULT hr = CreateDDSTextureFromFile( Graphics::g_device.Get(), FileName, 0, sRGB, &m_pResource, m_hCpuDescriptorHandle ); return SUCCEEDED( hr ); }
void Asteroids::CreateGUIResources() { auto font = mGUI->Font(); D3D11_TEXTURE2D_DESC textureDesc = CD3D11_TEXTURE2D_DESC(DXGI_FORMAT_A8_UNORM, font->BitmapWidth(), font->BitmapHeight(), 1, 1); D3D11_SUBRESOURCE_DATA initialData = {}; initialData.pSysMem = font->Pixels(); initialData.SysMemPitch = font->BitmapWidth(); ID3D11Texture2D* texture = nullptr; ThrowIfFailed(mDevice->CreateTexture2D(&textureDesc, &initialData, &texture)); ThrowIfFailed(mDevice->CreateShaderResourceView(texture, nullptr, &mFontTextureSRV)); SafeRelease(&texture); // Load any GUI sprite textures for (size_t i = 0; i < mGUI->size(); ++i) { auto control = (*mGUI)[i]; if (control->TextureFile().length() > 0 && mSpriteTextures.find(control->TextureFile()) == mSpriteTextures.end()) { std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter; ID3D11ShaderResourceView* textureSRV = nullptr; ThrowIfFailed(CreateDDSTextureFromFile(mDevice, converter.from_bytes(control->TextureFile()).c_str(), &textureSRV, true)); mSpriteTextures[control->TextureFile()] = textureSRV; } } }
VOID AEDataFileReader::loadResources(std::string fileName) { std::ifstream fs(fileName); if (fs.fail()) { AENSGameControl::exitGame("Cannot open file: " + fileName); } AERO_RESOURCE_DESC descRes; size_t newSizeW, convertedChars; std::string line, item; std::istringstream iss; while (!fs.eof()) { getline(fs, line); iss.clear(); iss.str(line); if (line == "") continue; iss >> item; descRes.rid = stoi(item); iss >> item; descRes.rtype = resourceTypeDecrypt(item); iss >> item; descRes.cellW = stoi(item); iss >> item; descRes.cellH = stoi(item); iss >> item; newSizeW = strlen(item.c_str()) + 1; convertedChars = 0; wchar_t* witem = new wchar_t[newSizeW]; mbstowcs_s(&convertedChars, witem, newSizeW, item.c_str(), _TRUNCATE); // Must convert std::string to wchar_t* HRESULT hr = CreateDDSTextureFromFile(g_pd3dDevice, witem, nullptr, &(descRes.tex)); if (FAILED(hr)) { AENSGameControl::exitGame("On loading texture: Texture load failed."); } ae_ResourceTable.addAt(descRes.rid, new AEResource(descRes)); } fs.close(); }
Material::Material(SimpleVertexShader* vShader, SimplePixelShader* pShader, ID3D11Device* device, ID3D11DeviceContext* deviceContext, const wchar_t* filePath, bool ddsFile) { vertexShader = vShader; pixelShader = pShader; file = filePath; //check for .dds file if (ddsFile){ CreateDDSTextureFromFile(device, deviceContext, filePath, 0, &SRV); } else { CreateWICTextureFromFile(device, deviceContext, filePath, 0, &SRV); } D3D11_SAMPLER_DESC sampleDescription = {}; // ZeroMemory(&sampleDescription, sizeof(sampleDescription)); sampleDescription.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; sampleDescription.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; sampleDescription.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; sampleDescription.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; sampleDescription.MaxLOD = D3D11_FLOAT32_MAX; device->CreateSamplerState(&sampleDescription, &samplerState); }
void initAll(ID3D11Device& device, ID3D11DeviceContext& context, ShaderResources& shaderResources) { assert(shaderResources.mDiffuseMapSRV == nullptr); assert(shaderResources.mCSResultsSRV == nullptr); assert(shaderResources.mCSResultsUAV == nullptr); ID3D11Resource* texture = nullptr; // // Diffuse Map // HRESULT result = CreateDDSTextureFromFile(&device, L"Resources/Textures/brick.dds", &texture, &shaderResources.mDiffuseMapSRV); DxErrorChecker(result); texture->Release(); // // Create compute shader texture // D3D11_TEXTURE2D_DESC groupResultsTexDesc; groupResultsTexDesc.Width = 512; groupResultsTexDesc.Height = 512; groupResultsTexDesc.MipLevels = 1; groupResultsTexDesc.ArraySize = 1; groupResultsTexDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; groupResultsTexDesc.SampleDesc.Count = 1; groupResultsTexDesc.SampleDesc.Quality = 0; groupResultsTexDesc.Usage = D3D11_USAGE_DEFAULT; groupResultsTexDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_UNORDERED_ACCESS; groupResultsTexDesc.CPUAccessFlags = 0; groupResultsTexDesc.MiscFlags = 0; ID3D11Texture2D* groupResultsTex = nullptr; assert(Globals::gDirect3DData.mDevice); result = device.CreateTexture2D(&groupResultsTexDesc, 0, &groupResultsTex); DxErrorChecker(result); D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc; srvDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; srvDesc.Texture2D.MostDetailedMip = 0; srvDesc.Texture2D.MipLevels = 1; result = device.CreateTexture2D(&groupResultsTexDesc, 0, &groupResultsTex); result = device.CreateShaderResourceView(groupResultsTex, &srvDesc, &shaderResources.mCSResultsSRV); D3D11_UNORDERED_ACCESS_VIEW_DESC uavDesc; uavDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; uavDesc.ViewDimension = D3D11_UAV_DIMENSION_TEXTURE2D; uavDesc.Texture2D.MipSlice = 0; result = device.CreateUnorderedAccessView(groupResultsTex, &uavDesc, &shaderResources.mCSResultsUAV); // Views save a reference to the texture so we can release our reference. groupResultsTex->Release(); }
void mirror::setSRV(wchar_t* _TexturefileName) { HRESULT hr; hr = CreateDDSTextureFromFile(m_d3d11Device, _TexturefileName, NULL, &m_SRV); if (FAILED(hr)) { assert(0); } }
void ResourcesManager::initAll(ID3D11Device* device, ID3D11DeviceContext* context) { assert(device); assert(context); ID3D11Resource* texture = nullptr; // Create grass texture shader resource view HRESULT result = CreateDDSTextureFromFile(device, L"Resources/Textures/sand.dds", &texture, &mSandSRV); DxErrorChecker(result); // Create sky cube map shader resource view result = CreateDDSTextureFromFile(device, L"Resources/Textures/desertcube1024.dds", &texture, &mSkyCubeMapSRV); DxErrorChecker(result); // Create sphere diffuse map texture result = CreateDDSTextureFromFile(device, L"Resources/Textures/stone.dds", &texture, &mSphereDiffuseMapSRV); DxErrorChecker(result); texture->Release(); }
HRESULT DrawableObject::CreateSpecularMap() { // Convert std:string to std::wstring std::wstring specularMap( m_meshInfo.specularMapName.begin(), m_meshInfo.specularMapName.end() ); // Read texture HRESULT hr = CreateDDSTextureFromFile( m_device , specularMap.c_str(), (ID3D11Resource**)&m_texture, nullptr ); if( FAILED( hr ) ) return hr; return hr = m_device->CreateShaderResourceView( m_texture, nullptr, &m_specularmapRCV ); }
bool Texture::loadDDS(ID3D11Device* device, wchar_t* filename) { HRESULT result; // Load the texture in. result = CreateDDSTextureFromFile(device, filename, NULL, &m_texture); if (FAILED(result)) { return false; } return true; }
void ResourcesManager::initAll(ID3D11Device* device, ID3D11DeviceContext* context) { assert(device); assert(context); ID3D11Resource* texture = nullptr; // Create diffuse and normal maps HRESULT result = CreateDDSTextureFromFile(device, L"Resources/Textures/wood1.dds", &texture, &mFloorDiffuseMapSRV); DxErrorChecker(result); result = CreateDDSTextureFromFile(device, L"Resources/Textures/wood1Normal.dds", &texture, &mFloorNormalMapSRV); DxErrorChecker(result); result = CreateDDSTextureFromFile(device, L"Resources/Textures/brick.dds", &texture, &mCylinderDiffuseMapSRV); DxErrorChecker(result); result = CreateDDSTextureFromFile(device, L"Resources/Textures/brickNormal.dds", &texture, &mCylinderNormalMapSRV); DxErrorChecker(result); texture->Release(); }
void TextureDemo::LoadTexture() { HRESULT hr = S_FALSE; hr = CreateDDSTextureFromFile(m_d3dDevice, L"Texture/PowerOfTheHorde.dds", nullptr, &m_texture); D3DHelper::ThrowIfFailed(hr); D3D11_SAMPLER_DESC sampleDesc; ZeroMemory(&sampleDesc, sizeof(D3D11_SAMPLER_DESC)); sampleDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; sampleDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; sampleDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; sampleDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; sampleDesc.MipLODBias = 0.0f; sampleDesc.MaxAnisotropy = 4; sampleDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS; sampleDesc.BorderColor[0] = 0; sampleDesc.BorderColor[1] = 0; sampleDesc.BorderColor[2] = 0; sampleDesc.BorderColor[3] = 0; sampleDesc.MinLOD = 0; sampleDesc.MaxLOD = D3D11_FLOAT32_MAX; hr = m_d3dDevice->CreateSamplerState(&sampleDesc, &m_wrapModeSampler); D3DHelper::ThrowIfFailed(hr); m_currentSamplerState = m_wrapModeSampler.Get(); sampleDesc.AddressU = D3D11_TEXTURE_ADDRESS_BORDER; sampleDesc.AddressV = D3D11_TEXTURE_ADDRESS_BORDER; sampleDesc.AddressW = D3D11_TEXTURE_ADDRESS_BORDER; hr = m_d3dDevice->CreateSamplerState(&sampleDesc, &m_boderColorModeSampler); D3DHelper::ThrowIfFailed(hr); sampleDesc.AddressU = D3D11_TEXTURE_ADDRESS_MIRROR; sampleDesc.AddressV = D3D11_TEXTURE_ADDRESS_MIRROR; sampleDesc.AddressW = D3D11_TEXTURE_ADDRESS_MIRROR; hr = m_d3dDevice->CreateSamplerState(&sampleDesc, &m_mirrorModeSampler); D3DHelper::ThrowIfFailed(hr); sampleDesc.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP; sampleDesc.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP; sampleDesc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP; hr = m_d3dDevice->CreateSamplerState(&sampleDesc, &m_clampModeSampler); D3DHelper::ThrowIfFailed(hr); m_constDiffuseLightReflect.DiffuseLightColor = (XMFLOAT4&)DirectX::Colors::White; m_constDiffuseLightReflect.LightDirection = { 0.0f, 0.0f, 1.0f }; m_constDiffuseLightReflect.Padding = 0.0f; }
void Material::Skybox (SimpleVertexShader** vert, SimplePixelShader** pix, ID3D11Device** device, ID3D11DeviceContext** deviceContext, ID3D11SamplerState** sampler, ID3D11ShaderResourceView** texSRV, ID3D11RasterizerState** rasState, ID3D11DepthStencilState** depthState, const wchar_t* texture) { vertexShader = *vert; pixelShader = *pix; _sampler = *sampler; isSkybox = true; _rasState = *rasState; _depthState = *depthState; CreateDDSTextureFromFile(*device, *deviceContext, texture, 0, texSRV); _skySRV = *texSRV; //pixelShader->SetShaderResourceView("skyTexture", *texSRV); //pixelShader->SetSamplerState("trillinear", samplerState); }
bool ModelMaterial::Initialize(ID3D11Device* a_pDevice, SceneSettings* a_pSceneSettings) { bool result; result = InitializeShader(a_pDevice, "../TexturedModelVS.cso", "../TexturedModelPS.cso"); if(!result) { return false; } m_pSceneSettings = a_pSceneSettings; CreateDDSTextureFromFile(a_pDevice, L"../Tiny_skin.dds", NULL, &m_pTexture); return true; }
//=============================================================================================================================== ID3D11ShaderResourceView* TextureManager::LoadSRV(LPCWSTR tex_filename, TextureType tt) { ID3D11ShaderResourceView* mTexture = 0; switch (tt) { case DDS: { HRESULT result; result = CreateDDSTextureFromFile(mD3DSystem->GetDevice11(), tex_filename, nullptr, &mTexture); if (FAILED(result)) { result = LoadDDSTextureFromFile(tex_filename, &mTexture); if (FAILED(result)) { return 0; } } } break; case TGA: { HRESULT result = CreateTGATextureFromFile(tex_filename, &mTexture); if (FAILED(result)) { return 0; } } break; case PNG: { HRESULT result; result = CreateWICTextureFromFile(mD3DSystem->GetDevice11(), tex_filename, nullptr, &mTexture); if (FAILED(result)) { result = LoadWICTextureFromFile(tex_filename, &mTexture); if (FAILED(result)) { return 0; } } } break; } return mTexture; }
HRESULT DrawableObject::CreateTextureAndSamplerState() /// NY { // Convert std:string to std::wstring std::wstring texture( m_meshInfo.textureName.begin(), m_meshInfo.textureName.end() ); // Read texture HRESULT hr = CreateDDSTextureFromFile( m_device , texture.c_str(), (ID3D11Resource**)&m_texture, nullptr ); if( FAILED( hr ) ) return hr; //============================== // Create Anisotropic Sampler || //============================== D3D11_SAMPLER_DESC samAniDesc; memset( &samAniDesc, 0, sizeof( samAniDesc ) ); samAniDesc.Filter = D3D11_FILTER_ANISOTROPIC; samAniDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; samAniDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; samAniDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; samAniDesc.MipLODBias = 0.0f; samAniDesc.MaxAnisotropy = 4; samAniDesc.ComparisonFunc = D3D11_COMPARISON_NEVER; if( FAILED( hr = m_device->CreateSamplerState( &samAniDesc, &m_samplerStateAnisotropic ) ) ) return hr; //============================== // Create Anisotropic Sampler || //============================== D3D11_SAMPLER_DESC samLinDesc; memset( &samLinDesc, 0, sizeof( samLinDesc ) ); samLinDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; samLinDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; samLinDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; samLinDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; samLinDesc.MipLODBias = 0.0f; samLinDesc.MaxAnisotropy = 1; samLinDesc.ComparisonFunc = D3D11_COMPARISON_NEVER; if( FAILED( hr = m_device->CreateSamplerState( &samLinDesc, &m_samplerStateLinear ) ) ) return hr; hr = m_device->CreateShaderResourceView( m_texture, nullptr, &m_shaderResourceView ); return hr; }
//-------------------------------------------------------------------------------------- // Create any D3D9 resources that won't live through a device reset (D3DPOOL_DEFAULT) // or that are tied to the back buffer size //-------------------------------------------------------------------------------------- HRESULT CALLBACK OnD3D9ResetDevice( IDirect3DDevice9* pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ) { HRESULT hr; V_RETURN( g_DialogResourceManager.OnD3D9ResetDevice() ); V_RETURN( g_SettingsDlg.OnD3D9ResetDevice() ); if( g_pFont9 ) V_RETURN( g_pFont9->OnResetDevice() ); if( g_pEffect9 ) V_RETURN( g_pEffect9->OnResetDevice() ); V_RETURN( D3DXCreateSprite( pd3dDevice, &g_pSprite9 ) ); g_pTxtHelper = new CDXUTTextHelper( g_pFont9, g_pSprite9, NULL, NULL, 15 ); // Setup the camera's projection parameters float fAspectRatio = pBackBufferSurfaceDesc->Width / ( FLOAT )pBackBufferSurfaceDesc->Height; g_Camera.SetProjParams( D3DX_PI / 4, fAspectRatio, 0.1f, 1000.0f ); g_Camera.SetWindow( pBackBufferSurfaceDesc->Width, pBackBufferSurfaceDesc->Height ); g_HUD.SetLocation( pBackBufferSurfaceDesc->Width - 170, 0 ); g_HUD.SetSize( 170, 170 ); g_SampleUI.SetLocation( pBackBufferSurfaceDesc->Width - 170, pBackBufferSurfaceDesc->Height - 350 ); g_SampleUI.SetSize( 170, 300 ); // load the mesh V_RETURN( g_Mesh.Create( pd3dDevice, L"misc\\ball.sdkmesh" ) ); // Load the texture WCHAR str[MAX_PATH]; V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"misc\\seafloor.dds" ) ); V_RETURN( CreateDDSTextureFromFile( pd3dDevice, str, &g_pTexture9 ) ); if( DXUTIsWindowed() ) g_SampleUI.GetButton( IDC_LOAD_TEXTURE )->SetEnabled( true ); else g_SampleUI.GetButton( IDC_LOAD_TEXTURE )->SetEnabled( false ); return S_OK; }
bool Texture::Initialize(ID3D11Device* device, WCHAR* filename) { HRESULT result; // Load the texture in. result = CreateDDSTextureFromFile(device, filename, NULL, &texture, NULL); if(FAILED(result)) { return false; } return true; //unique_ptr<ScratchImage> image (new ScratchImage); //ScratchImage //unique_p //HRESULT result = LoadFromWICFile(filename, WIC_FLAGS_NONE, nullptr, *image); }
Asteroids::Asteroids(AsteroidsSimulation* asteroids, GUI* gui, bool warp) : mAsteroids(asteroids) , mGUI(gui) , mSwapChain(nullptr) , mDevice(nullptr) , mDeviceCtxt(nullptr) , mRenderTarget(nullptr) , mRenderTargetView(nullptr) , mDepthStencilView(nullptr) , mDepthStencilState(nullptr) , mInputLayout(nullptr) , mIndexBuffer(nullptr) , mVertexBuffer(nullptr) , mVertexShader(nullptr) , mPixelShader(nullptr) , mDrawConstantBuffer(nullptr) , mSkyboxVertexShader(nullptr) , mSkyboxPixelShader(nullptr) , mSkyboxConstantBuffer(nullptr) , mSamplerState(nullptr) { memset(&mViewPort, 0, sizeof(mViewPort)); memset(&mScissorRect, 0, sizeof(mScissorRect)); memset(mTextures, 0, sizeof(mTextures)); memset(mTextureSRVs, 0, sizeof(mTextureSRVs)); // Create device and swap chain { IDXGIAdapter* adapter = nullptr; D3D_DRIVER_TYPE driverType = ( warp ) ? D3D_DRIVER_TYPE_WARP : D3D_DRIVER_TYPE_HARDWARE; HMODULE swModule = NULL; UINT flags = 0; D3D_FEATURE_LEVEL featureLevels[] = { D3D_FEATURE_LEVEL_11_0 }; UINT numFeatureLevels = ARRAYSIZE(featureLevels); UINT sdkVersion = D3D11_SDK_VERSION; #ifdef _DEBUG flags = flags | D3D11_CREATE_DEVICE_DEBUG; #endif auto hr = D3D11CreateDevice(adapter, driverType, swModule, flags, featureLevels, numFeatureLevels, sdkVersion, &mDevice, nullptr, &mDeviceCtxt); if (FAILED(hr)) { // Try again without the debug flag... flags = flags & ~D3D11_CREATE_DEVICE_DEBUG; ThrowIfFailed(D3D11CreateDevice(adapter, driverType, swModule, flags, featureLevels, numFeatureLevels, sdkVersion, &mDevice, nullptr, &mDeviceCtxt)); } } // create pipeline state { D3D11_INPUT_ELEMENT_DESC inputDesc[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; ThrowIfFailed(mDevice->CreateInputLayout(inputDesc, ARRAYSIZE(inputDesc), g_asteroid_vs, sizeof(g_asteroid_vs), &mInputLayout)); { D3D11_DEPTH_STENCIL_DESC desc = CD3D11_DEPTH_STENCIL_DESC(D3D11_DEFAULT); desc.DepthFunc = D3D11_COMPARISON_GREATER_EQUAL; ThrowIfFailed(mDevice->CreateDepthStencilState(&desc, &mDepthStencilState)); } { CD3D11_BLEND_DESC desc = CD3D11_BLEND_DESC(CD3D11_DEFAULT()); ThrowIfFailed(mDevice->CreateBlendState(&desc, &mBlendState)); // Premultiplied over blend desc.RenderTarget[0].BlendEnable = TRUE; desc.RenderTarget[0].SrcBlend = D3D11_BLEND_ONE; desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; desc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA; ThrowIfFailed(mDevice->CreateBlendState(&desc, &mSpriteBlendState)); } ThrowIfFailed(mDevice->CreateVertexShader(g_asteroid_vs, sizeof(g_asteroid_vs), NULL, &mVertexShader)); ThrowIfFailed(mDevice->CreatePixelShader(g_asteroid_ps_d3d11, sizeof(g_asteroid_ps_d3d11), NULL, &mPixelShader)); } // create skybox pipeline state { D3D11_INPUT_ELEMENT_DESC inputDesc[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "UVFACE", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; ThrowIfFailed(mDevice->CreateInputLayout(inputDesc, ARRAYSIZE(inputDesc), g_skybox_vs, sizeof(g_skybox_vs), &mSkyboxInputLayout)); ThrowIfFailed(mDevice->CreateVertexShader(g_skybox_vs, sizeof(g_skybox_vs), NULL, &mSkyboxVertexShader)); ThrowIfFailed(mDevice->CreatePixelShader(g_skybox_ps, sizeof(g_skybox_ps), NULL, &mSkyboxPixelShader)); } // Sprites and fonts { D3D11_INPUT_ELEMENT_DESC inputDesc[] = { { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "UV", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 8, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; ThrowIfFailed(mDevice->CreateInputLayout(inputDesc, ARRAYSIZE(inputDesc), g_sprite_vs, sizeof(g_sprite_vs), &mSpriteInputLayout)); ThrowIfFailed(mDevice->CreateVertexShader(g_sprite_vs, sizeof(g_sprite_vs), NULL, &mSpriteVertexShader)); ThrowIfFailed(mDevice->CreatePixelShader(g_sprite_ps, sizeof(g_sprite_ps), NULL, &mSpritePixelShader)); ThrowIfFailed(mDevice->CreatePixelShader(g_font_ps, sizeof(g_font_ps), NULL, &mFontPixelShader)); } // Create draw constant buffer { D3D11_BUFFER_DESC desc = {}; desc.Usage = D3D11_USAGE_DYNAMIC; desc.ByteWidth = sizeof(DrawConstantBuffer); desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; ThrowIfFailed(mDevice->CreateBuffer(&desc, nullptr, &mDrawConstantBuffer)); } // Create skybox constant buffer { D3D11_BUFFER_DESC desc = {}; desc.Usage = D3D11_USAGE_DYNAMIC; desc.ByteWidth = sizeof(SkyboxConstantBuffer); desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; ThrowIfFailed(mDevice->CreateBuffer(&desc, nullptr, &mSkyboxConstantBuffer)); } // Create sampler { D3D11_SAMPLER_DESC desc = {}; desc.Filter = D3D11_FILTER_ANISOTROPIC; desc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; desc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; desc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; desc.MinLOD = -D3D11_FLOAT32_MAX; desc.MaxLOD = D3D11_FLOAT32_MAX; desc.MipLODBias = 0.0f; desc.MaxAnisotropy = TEXTURE_ANISO; desc.ComparisonFunc = D3D11_COMPARISON_NEVER; ThrowIfFailed(mDevice->CreateSamplerState(&desc, &mSamplerState)); } CreateMeshes(); InitializeTextureData(); CreateGUIResources(); // Load textures ThrowIfFailed(CreateDDSTextureFromFile(mDevice, L"starbox_1024.dds", &mSkyboxSRV, true)); }
void Hill::init_texture(ID3D11Device *pD3D11Device) { CreateDDSTextureFromFile(pD3D11Device, L"../../media/textures/grass1.dds", 0, &m_pGrassSRV); CreateDDSTextureFromFile(pD3D11Device, L"../../media/textures/water2.dds", 0, &m_pWaveSRV); }
HRESULT FileReader::ReadMaterial(ID3D11Device* device, std::string filename, std::vector<std::string> materialNames, std::vector<Material> &outMaterials, std::vector<ID3D11ShaderResourceView*> &textureViews) { HRESULT hr = S_OK; FILE * file; fopen_s(&file,filename.c_str(), "r"); if( file == NULL ) { printf("Impossible to open the file !\n"); return false; } std::vector<MatGroup> matGroups; ID3D11ShaderResourceView* tempResource; std::string tempName; Material tempMat; tempMat.Ambient = XMFLOAT4(0,0,0,0); tempMat.Diffuse = XMFLOAT4(0,0,0,0); tempMat.Specular = XMFLOAT4(0,0,0,0); tempMat.Transmission = XMFLOAT4(0,0,0,0); bool firstMat = true; while(true) { char lineHeader[128]; // read the first word of the line int res = fscanf_s(file, "%s", lineHeader, _countof(lineHeader)); if (res == EOF) { break; // EOF = End Of File. Quit the loop. } else if ( strcmp( lineHeader, "newmtl" ) == 0 ) { char tempN[128]; int outp = fscanf_s(file, "%s\n", tempN, _countof(tempN)); if(outp != 1) { return false; //I guess? } if(!firstMat) { MatGroup temp; temp.name = tempName; temp.mMaterial = tempMat; temp.tempResource = tempResource; matGroups.push_back(temp); outMaterials.push_back(tempMat); tempMat.Ambient = XMFLOAT4(0,0,0,0); tempMat.Diffuse = XMFLOAT4(0,0,0,0); tempMat.Specular = XMFLOAT4(0,0,0,0); tempMat.Transmission = XMFLOAT4(0,0,0,0); } else { firstMat = false; } tempName = tempN; } else if ( strcmp( lineHeader, "Ks" ) == 0 ) //diffuse color { XMFLOAT4 specCol; fscanf_s(file, "%f %f %f\n", &specCol.x, &specCol.y, &specCol.z ); specCol.w = 1; tempMat.Diffuse = specCol; } else if ( strcmp( lineHeader, "Kd" ) == 0 ) //diffuse color { XMFLOAT4 difCol; fscanf_s(file, "%f %f %f\n", &difCol.x, &difCol.y, &difCol.z ); difCol.w = 1; tempMat.Diffuse = difCol; } else if ( strcmp( lineHeader, "Ka" ) == 0 ) //ambient { XMFLOAT4 ambCol; fscanf_s(file, "%f %f %f\n", &ambCol.x, &ambCol.y, &ambCol.z ); ambCol.w = 1; tempMat.Diffuse = ambCol; } else if ( strcmp( lineHeader, "Tf" ) == 0 ) //transmission filter { XMFLOAT4 trans; fscanf_s(file, "%f %f %f\n", &trans.x, &trans.y, &trans.z ); trans.w = 1; tempMat.Transmission = trans; } else if ( strcmp( lineHeader, "map_Kd" ) == 0 ) { char temp[128]; int outp = fscanf_s(file, "%s\n", temp, _countof(temp)); if(outp != 1) { return false; //I guess? } while(outMaterials.size()> textureViews.size()) { textureViews.push_back(nullptr); //dont think this works } size_t newsize = strlen(temp) + 1; wchar_t * texName = new wchar_t[newsize]; size_t convertedChars = 0; mbstowcs_s(&convertedChars, texName, newsize, temp, _TRUNCATE); hr = CreateDDSTextureFromFile(device , texName, nullptr, &tempResource); delete(texName); } } MatGroup temp; temp.name = tempName; temp.mMaterial = tempMat; temp.tempResource = tempResource; matGroups.push_back(temp); for (int i = 0; i < materialNames.size(); i++) { for (int j = 0; j < matGroups.size(); j++) { if(materialNames[i] == matGroups[i].name) { outMaterials.push_back(matGroups[j].mMaterial); textureViews.push_back(matGroups[j].tempResource); } else { } } } return hr; }
HRESULT Application::InitDevice() { HRESULT hr = S_OK; UINT createDeviceFlags = 0; #ifdef _DEBUG createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG; #endif D3D_DRIVER_TYPE driverTypes[] = { D3D_DRIVER_TYPE_HARDWARE, D3D_DRIVER_TYPE_WARP, D3D_DRIVER_TYPE_REFERENCE, }; UINT numDriverTypes = ARRAYSIZE(driverTypes); D3D_FEATURE_LEVEL featureLevels[] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0, }; UINT numFeatureLevels = ARRAYSIZE(featureLevels); DXGI_SWAP_CHAIN_DESC sd; ZeroMemory(&sd, sizeof(sd)); sd.BufferCount = 1; sd.BufferDesc.Width = _WindowWidth; sd.BufferDesc.Height = _WindowHeight; sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; sd.BufferDesc.RefreshRate.Numerator = 60; sd.BufferDesc.RefreshRate.Denominator = 1; sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; sd.OutputWindow = _hWnd; sd.SampleDesc.Count = 1; sd.SampleDesc.Quality = 0; sd.Windowed = TRUE; for (UINT driverTypeIndex = 0; driverTypeIndex < numDriverTypes; driverTypeIndex++) { _driverType = driverTypes[driverTypeIndex]; hr = D3D11CreateDeviceAndSwapChain(nullptr, _driverType, nullptr, createDeviceFlags, featureLevels, numFeatureLevels, D3D11_SDK_VERSION, &sd, &_pSwapChain, &_pd3dDevice, &_featureLevel, &_pImmediateContext); if (SUCCEEDED(hr)) break; } if (FAILED(hr)) return hr; // Create a render target view ID3D11Texture2D* pBackBuffer = nullptr; hr = _pSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pBackBuffer); if (FAILED(hr)) return hr; hr = _pd3dDevice->CreateRenderTargetView(pBackBuffer, nullptr, &_pRenderTargetView); pBackBuffer->Release(); if (FAILED(hr)) return hr; D3D11_TEXTURE2D_DESC depthStencilDesc; depthStencilDesc.Width = _WindowWidth; depthStencilDesc.Height = _WindowHeight; depthStencilDesc.MipLevels = 1; depthStencilDesc.ArraySize = 1; depthStencilDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; depthStencilDesc.SampleDesc.Count = 1; depthStencilDesc.SampleDesc.Quality = 0; depthStencilDesc.Usage = D3D11_USAGE_DEFAULT; depthStencilDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL; depthStencilDesc.CPUAccessFlags = 0; depthStencilDesc.MiscFlags = 0; _pd3dDevice->CreateTexture2D(&depthStencilDesc, nullptr, &_depthStencilBuffer); _pd3dDevice->CreateDepthStencilView(_depthStencilBuffer, nullptr, &_depthStencilView); _pImmediateContext->OMSetRenderTargets(1, &_pRenderTargetView, _depthStencilView); // Setup the viewport D3D11_VIEWPORT vp; vp.Width = (FLOAT)_WindowWidth; vp.Height = (FLOAT)_WindowHeight; vp.MinDepth = 0.0f; vp.MaxDepth = 1.0f; vp.TopLeftX = 0; vp.TopLeftY = 0; _pImmediateContext->RSSetViewports(1, &vp); InitShadersAndInputLayout(); //Set the vertex buffers InitVertexBuffer(); InitGridVertexBuffer(); // Set the index buffers InitIndexBuffer(); InitGridIndexBuffer(); // Set primitive topology _pImmediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); // Create the constant buffer D3D11_BUFFER_DESC bd; ZeroMemory(&bd, sizeof(bd)); bd.Usage = D3D11_USAGE_DEFAULT; bd.ByteWidth = sizeof(ConstantBuffer); bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER; bd.CPUAccessFlags = 0; hr = _pd3dDevice->CreateBuffer(&bd, nullptr, &_pConstantBuffer); if (FAILED(hr)) return hr; // Creates the wireframe Rasterizer Desc D3D11_RASTERIZER_DESC wfdesc; ZeroMemory(&wfdesc, sizeof(D3D11_RASTERIZER_DESC)); wfdesc.FillMode = D3D11_FILL_WIREFRAME; wfdesc.CullMode = D3D11_CULL_NONE; hr = _pd3dDevice->CreateRasterizerState(&wfdesc, &_wireFrame); //Creates the solid fill Rasterizer desc D3D11_RASTERIZER_DESC wfdesc2; ZeroMemory(&wfdesc2, sizeof(D3D11_RASTERIZER_DESC)); wfdesc2.FillMode = D3D11_FILL_SOLID; wfdesc2.CullMode = D3D11_CULL_BACK; hr = _pd3dDevice->CreateRasterizerState(&wfdesc2, &_solidFill); D3D11_SAMPLER_DESC sampDesc; ZeroMemory(&sampDesc, sizeof(sampDesc)); sampDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; sampDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; sampDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; sampDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; sampDesc.ComparisonFunc = D3D11_COMPARISON_NEVER; sampDesc.MinLOD = 0; sampDesc.MaxLOD = D3D11_FLOAT32_MAX; _pd3dDevice->CreateSamplerState(&sampDesc, &_pSamplerLinear); //Loads the textures for objects CreateDDSTextureFromFile(_pd3dDevice, L"textures/Crate_COLOR.dds", nullptr, &_pTextureRV); CreateDDSTextureFromFile(_pd3dDevice, L"textures/Pine Tree.dds", nullptr, &_pTreeTextureRV); CreateDDSTextureFromFile(_pd3dDevice, L"textures/grass.dds", nullptr, &_grassTextureRV); CreateDDSTextureFromFile(_pd3dDevice, L"textures/Hercules_COLOR.dds", nullptr, &_planeTextureRV); CreateDDSTextureFromFile(_pd3dDevice, L"textures/ocean.dds", nullptr, &_oceanTextureRV); CreateDDSTextureFromFile(_pd3dDevice, L"textures/sky.dds", nullptr, &_skyTextureRV); CreateDDSTextureFromFile(_pd3dDevice, L"textures/brick.dds", nullptr, &_buildingTextureRV); D3D11_BLEND_DESC blendDesc; ZeroMemory(&blendDesc, sizeof(blendDesc)); D3D11_RENDER_TARGET_BLEND_DESC rtbd; ZeroMemory(&rtbd, sizeof(rtbd)); rtbd.BlendEnable = true; rtbd.SrcBlend = D3D11_BLEND_SRC_COLOR; rtbd.DestBlend = D3D11_BLEND_BLEND_FACTOR; rtbd.BlendOp = D3D11_BLEND_OP_ADD; rtbd.SrcBlendAlpha = D3D11_BLEND_ONE; rtbd.DestBlendAlpha = D3D11_BLEND_ZERO; rtbd.BlendOpAlpha = D3D11_BLEND_OP_ADD; rtbd.RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL; blendDesc.AlphaToCoverageEnable = false; blendDesc.RenderTarget[0] = rtbd; _pd3dDevice->CreateBlendState(&blendDesc, &Transparency); return S_OK; }
void LoadMaterials(ID3D11Device* d3dDevice, int inIndex, DrawableObject &inObject, const aiScene *inScene) { aiString texPath, normTexPath; aiReturn hasTex = inScene->mMaterials[inIndex]->GetTexture(aiTextureType_DIFFUSE, 0, &texPath); if (hasTex == AI_SUCCESS) { wchar_t texPathW[150]; //std::string texPathString = "dabrovic-sponza/01_STUB.dds"; MultiByteToWideChar(CP_ACP, 0, texPath.C_Str(), -1, texPathW, 150); ID3D11Resource *texture, *textureNorm; ID3D11ShaderResourceView *newDiffuseShaderResourceView, *newNormalMapShaderResourceView; HRESULT hr = CreateDDSTextureFromFile(d3dDevice, texPathW, &texture, &newDiffuseShaderResourceView); if (FAILED(hr)) { CreateDDSTextureFromFile(d3dDevice, L"texture_missing.dds", &texture, &newDiffuseShaderResourceView); std::stringstream oss; oss << "ERROR - Texture: " << texPathW << " not found." << std::endl; std::string debugMsg(oss.str()); OutputDebugStringA(debugMsg.c_str()); } std::string normTexPath = std::string(texPath.C_Str()); normTexPath.resize(normTexPath.length() - 4); // remove the .dds normTexPath += "_normal.dds"; //normTexPath = "dabrovic-sponza/01_STUB_normal.dds"; MultiByteToWideChar(CP_ACP, 0, normTexPath.c_str(), -1, texPathW, 150); hr = CreateDDSTextureFromFile(d3dDevice, texPathW, &textureNorm, &newNormalMapShaderResourceView); if (FAILED(hr)) { std::stringstream oss; oss << "ERROR - Normal Texture: " << texPathW << " not found." << std::endl; std::string debugMsg(oss.str()); OutputDebugStringA(debugMsg.c_str()); CreateDDSTextureFromFile(d3dDevice, L"texture_missing_normal.dds", &textureNorm, &newNormalMapShaderResourceView); } D3D11_SAMPLER_DESC textureSamplerDesc; ZeroMemory(&textureSamplerDesc, sizeof(textureSamplerDesc)); textureSamplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; textureSamplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; textureSamplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; textureSamplerDesc.ComparisonFunc = D3D11_COMPARISON_NEVER; textureSamplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; textureSamplerDesc.MaxLOD = D3D11_FLOAT32_MAX; ID3D11SamplerState *newSamplerState; d3dDevice->CreateSamplerState(&textureSamplerDesc, &newSamplerState); ZeroMemory(&textureSamplerDesc, sizeof(textureSamplerDesc)); textureSamplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_BORDER; textureSamplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_BORDER; textureSamplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_BORDER; textureSamplerDesc.ComparisonFunc = D3D11_COMPARISON_LESS_EQUAL; textureSamplerDesc.Filter = D3D11_FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT; ZeroMemory(textureSamplerDesc.BorderColor, 4); ID3D11SamplerState *newShadowSamplerState; d3dDevice->CreateSamplerState(&textureSamplerDesc, &newShadowSamplerState); D3D11_TEXTURE2D_DESC textureDesc; reinterpret_cast<ID3D11Texture2D*>(texture)->GetDesc(&textureDesc); texture->Release(); reinterpret_cast<ID3D11Texture2D*>(textureNorm)->GetDesc(&textureDesc); textureNorm->Release(); inObject.AddTexture(newDiffuseShaderResourceView, newNormalMapShaderResourceView); inObject.SetTextureSamplerState(newSamplerState); inObject.SetShadowSamplerState(newShadowSamplerState); } hasTex = inScene->mMaterials[inIndex]->GetTexture(aiTextureType_NORMALS, 0, &texPath); if (hasTex == AI_SUCCESS) { wchar_t texPathW[100]; MultiByteToWideChar(CP_ACP, 0, texPath.C_Str(), -1, texPathW, 100); ID3D11Resource *texture0; ID3D11ShaderResourceView *newShaderResourceView; HRESULT hr = CreateDDSTextureFromFile(d3dDevice, texPathW, &texture0, &newShaderResourceView); if (FAILED(hr)) { CreateDDSTextureFromFile(d3dDevice, L"texture_missing.dds", &texture0, &newShaderResourceView); } D3D11_SAMPLER_DESC textureSamplerDesc; ZeroMemory(&textureSamplerDesc, sizeof(textureSamplerDesc)); textureSamplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; textureSamplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; textureSamplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; textureSamplerDesc.ComparisonFunc = D3D11_COMPARISON_NEVER; textureSamplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; textureSamplerDesc.MaxLOD = D3D11_FLOAT32_MAX; ID3D11SamplerState *newSamplerState; d3dDevice->CreateSamplerState(&textureSamplerDesc, &newSamplerState); D3D11_TEXTURE2D_DESC textureDesc; reinterpret_cast<ID3D11Texture2D*>(texture0)->GetDesc(&textureDesc); texture0->Release(); //inObject.SetDiffuseResourceView(newShaderResourceView); inObject.SetTextureSamplerState(newSamplerState); } aiColor3D ambientColor, diffuseColor, specularColor; float shininess; inScene->mMaterials[inIndex]->Get(AI_MATKEY_COLOR_AMBIENT, ambientColor); inScene->mMaterials[inIndex]->Get(AI_MATKEY_COLOR_DIFFUSE, diffuseColor); inScene->mMaterials[inIndex]->Get(AI_MATKEY_COLOR_SPECULAR, specularColor); inScene->mMaterials[inIndex]->Get(AI_MATKEY_SHININESS, shininess); inObject.SetMaterial(ambientColor, diffuseColor, specularColor, shininess); }
HRESULT Application::Initialise(HINSTANCE hInstance, int nCmdShow) { if (FAILED(InitWindow(hInstance, nCmdShow))) { return E_FAIL; } RECT rc; GetClientRect(_hWnd, &rc); _WindowWidth = rc.right - rc.left; _WindowHeight = rc.bottom - rc.top; if (FAILED(InitDevice())) { Cleanup(); return E_FAIL; } CreateDDSTextureFromFile(_pd3dDevice, L"Resources\\stone.dds", nullptr, &_pTextureRV); CreateDDSTextureFromFile(_pd3dDevice, L"Resources\\floor.dds", nullptr, &_pGroundTextureRV); objMeshData = OBJLoader::Load("sphere.obj", _pd3dDevice); // Setup Camera XMFLOAT3 eye = XMFLOAT3(0.0f, 2.0f, -1.0f); XMFLOAT3 at = XMFLOAT3(0.0f, 2.0f, 0.0f); XMFLOAT3 up = XMFLOAT3(0.0f, 1.0f, 0.0f); _camera = new Camera(eye, at, up, (float)_renderWidth, (float)_renderHeight, 0.01f, 200.0f); // Setup the scene's light basicLight.AmbientLight = XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f); basicLight.DiffuseLight = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f); basicLight.SpecularLight = XMFLOAT4(0.8f, 0.8f, 0.8f, 1.0f); basicLight.SpecularPower = 20.0f; basicLight.LightVecW = XMFLOAT3(0.0f, 1.0f, -1.0f); Geometry cubeGeometry; cubeGeometry.indexBuffer = _pIndexBuffer; cubeGeometry.vertexBuffer = _pVertexBuffer; cubeGeometry.numberOfIndices = 36; cubeGeometry.vertexBufferOffset = 0; cubeGeometry.vertexBufferStride = sizeof(SimpleVertex); Geometry planeGeometry; planeGeometry.indexBuffer = _pPlaneIndexBuffer; planeGeometry.vertexBuffer = _pPlaneVertexBuffer; planeGeometry.numberOfIndices = 6; planeGeometry.vertexBufferOffset = 0; planeGeometry.vertexBufferStride = sizeof(SimpleVertex); Geometry sphereGeometry; sphereGeometry.indexBuffer = objMeshData.IndexBuffer; sphereGeometry.vertexBuffer = objMeshData.VertexBuffer; sphereGeometry.numberOfIndices = objMeshData.IndexCount; sphereGeometry.vertexBufferOffset = objMeshData.VBOffset; sphereGeometry.vertexBufferStride = objMeshData.VBStride; Material shinyMaterial; shinyMaterial.ambient = XMFLOAT4(0.3f, 0.3f, 0.3f, 1.0f); shinyMaterial.diffuse = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f); shinyMaterial.specular = XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f); shinyMaterial.specularPower = 10.0f; Material noSpecMaterial; noSpecMaterial.ambient = XMFLOAT4(0.1f, 0.1f, 0.1f, 1.0f); noSpecMaterial.diffuse = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f); noSpecMaterial.specular = XMFLOAT4(0.0f, 0.0f, 0.0f, 0.0f); noSpecMaterial.specularPower = 0.0f; Appearance * floorAppearance = new Appearance(planeGeometry, noSpecMaterial); floorAppearance->SetTextureRV(_pGroundTextureRV); Appearance * crateAppearance = new Appearance(cubeGeometry, shinyMaterial); crateAppearance->SetTextureRV(_pTextureRV); Appearance * sphereAppearance = new Appearance(sphereGeometry, shinyMaterial); sphereAppearance->SetTextureRV(_pTextureRV); Transform * floorTransform = new Transform(); floorTransform->SetPosition(0.0f, 0.0f, 0.0f); floorTransform->SetScale(15.0f, 15.0f, 15.0f); floorTransform->SetRotation(XMConvertToRadians(90.0f), 0.0f, 0.0f); Transform * sphereTransform = new Transform(); sphereTransform->SetPosition(0.0f, 1.0f, 0.0f); ParticleModel * particleModel = new ParticleModel(floorTransform, false, XMFLOAT3(0.0f, 0.0f, 0.0f), XMFLOAT3(0.0f, 0.0f, 0.0f)); GameObject * gameObject = new GameObject("Floor", floorAppearance, floorTransform, particleModel); _gameObjects.push_back(gameObject); for (auto i = 0; i < 5; i++) { Transform * cubeTransform = new Transform(); cubeTransform->SetScale(0.5f, 0.5f, 0.5f); cubeTransform->SetPosition(-4.0f + (i * 2.0f), 0.5f, 10.0f); ParticleModel * particleModel = new ParticleModel(cubeTransform, true, XMFLOAT3(0.0f, 0.0f, 0.0f), XMFLOAT3(0.0f, 0.0f, 0.0f)); gameObject = new GameObject("Cube " + i, crateAppearance, cubeTransform, particleModel); _gameObjects.push_back(gameObject); } ParticleModel * particleModel2 = new ParticleModel(sphereTransform, false, XMFLOAT3(0.0f, 0.0f, 0.0f), XMFLOAT3(0.0f, 0.0f, 0.0f)); gameObject = new GameObject("Sphere", sphereAppearance, sphereTransform, particleModel2); _gameObjects.push_back(gameObject); // Setup specific cube behaviour _gameObjects[3]->GetParticleModel()->SetUsingConstAccel(false); _gameObjects[3]->GetParticleModel()->SetVelocity(0.0f, 0.1f, 0.0f); _gameObjects[4]->GetParticleModel()->SetAcceleration(0.0f, 0.1f, 0.0f); return S_OK; }
void SpecularLightingDemo::Initialize() { // Load a compiled vertex shader vector<char> compiledVertexShader; Utility::LoadBinaryFile(L"Content\\Shaders\\SpecularLightingDemoVS.cso", compiledVertexShader); ThrowIfFailed(mGame->Direct3DDevice()->CreateVertexShader(&compiledVertexShader[0], compiledVertexShader.size(), nullptr, mVertexShader.ReleaseAndGetAddressOf()), "ID3D11Device::CreatedVertexShader() failed."); // Load a compiled pixel shader vector<char> compiledPixelShader; Utility::LoadBinaryFile(L"Content\\Shaders\\SpecularLightingDemoPS.cso", compiledPixelShader); ThrowIfFailed(mGame->Direct3DDevice()->CreatePixelShader(&compiledPixelShader[0], compiledPixelShader.size(), nullptr, mPixelShader.ReleaseAndGetAddressOf()), "ID3D11Device::CreatedPixelShader() failed."); // Create an input layout D3D11_INPUT_ELEMENT_DESC inputElementDescriptions[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_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 }, }; ThrowIfFailed(mGame->Direct3DDevice()->CreateInputLayout(inputElementDescriptions, ARRAYSIZE(inputElementDescriptions), &compiledVertexShader[0], compiledVertexShader.size(), mInputLayout.ReleaseAndGetAddressOf()), "ID3D11Device::CreateInputLayout() failed."); // Load the model unique_ptr<Library::Model> model = make_unique<Library::Model>("Content\\Models\\Sphere.obj.bin"); // Create vertex and index buffers for the model Mesh* mesh = model->Meshes().at(0).get(); CreateVertexBuffer(*mesh, mVertexBuffer.ReleaseAndGetAddressOf()); mesh->CreateIndexBuffer(*mGame->Direct3DDevice(), mIndexBuffer.ReleaseAndGetAddressOf()); mIndexCount = static_cast<UINT>(mesh->Indices().size()); D3D11_BUFFER_DESC constantBufferDesc = { 0 }; constantBufferDesc.ByteWidth = sizeof(VertexCBufferPerObject); constantBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; ThrowIfFailed(mGame->Direct3DDevice()->CreateBuffer(&constantBufferDesc, nullptr, mVSConstantBufferPO.ReleaseAndGetAddressOf()), "ID3D11Device::CreateBuffer() failed."); constantBufferDesc.ByteWidth = sizeof(VertexCBufferPerFrame); ThrowIfFailed(mGame->Direct3DDevice()->CreateBuffer(&constantBufferDesc, nullptr, mVSConstantBufferPF.ReleaseAndGetAddressOf()), "ID3D11Device::CreateBuffer() failed."); constantBufferDesc.ByteWidth = sizeof(PixelCBufferPerFrame); ThrowIfFailed(mGame->Direct3DDevice()->CreateBuffer(&constantBufferDesc, nullptr, mPSConstantBufferPF.ReleaseAndGetAddressOf()), "ID3D11Device::CreateBuffer() failed."); constantBufferDesc.ByteWidth = sizeof(PixelCBufferPerObject); ThrowIfFailed(mGame->Direct3DDevice()->CreateBuffer(&constantBufferDesc, nullptr, mPSConstantBufferPO.ReleaseAndGetAddressOf()), "ID3D11Device::CreateBuffer() failed."); // Load a texture wstring textureName = L"Content\\Textures\\Earthatday.dds"; ThrowIfFailed(CreateDDSTextureFromFile(mGame->Direct3DDevice(), textureName.c_str(), nullptr, mColorTexture.ReleaseAndGetAddressOf()), "CreateDDSTextureFromFile() failed."); mSpriteBatch = std::make_unique<SpriteBatch>(mGame->Direct3DDeviceContext()); mSpriteFont = std::make_unique<SpriteFont>(mGame->Direct3DDevice(), L"Content\\Fonts\\Arial_14_Regular.spritefont"); //Create DirectionalLight mDirectionalLight = std::make_unique<DirectionalLight>(*mGame); mPSCBufferPerFrame.LightDirection = mDirectionalLight->DirectionToLight(); mPSCBufferPerObject.SpecularPower = 25.0f; XMStoreFloat3(&mPSCBufferPerObject.SpecularColor, DirectX::Colors::White); XMStoreFloat4(&mPSCBufferPerFrame.AmbientColor, DirectX::Colors::Black); XMStoreFloat4(&mPSCBufferPerFrame.LightColor, DirectX::Colors::White); // Load a proxy model for the directional light mProxyModel = make_unique<ProxyModel>(*mGame, mCamera, "Content\\Models\\DirectionalLightProxy.obj.bin", 0.5f); mProxyModel->Initialize(); mProxyModel->SetPosition(10.0f, 0.0, 0.0f); mProxyModel->ApplyRotation(XMMatrixRotationY(XM_PIDIV2)); // Locate possible input devices mKeyboard = static_cast<KeyboardComponent*>(mGame->Services().GetService(KeyboardComponent::TypeIdClass())); mGamePad = static_cast<GamePadComponent*>(mGame->Services().GetService(GamePadComponent::TypeIdClass())); }
//=============================================================================================================================== bool TextureManager::loadTexture(BetterString filename, ID3D11Texture2D** texture, int& textureDataSize, byte*& srcTextureData, TextureType tt) { ID3D11Device* device = mD3DSystem->GetDevice11(); ID3D11DeviceContext* immediateContext = mD3DSystem->GetDeviceContext(); ID3D11Texture2D* tempTexture; //string file = "Textures\\"; //file += filename.toString(); HRESULT hr = E_FAIL; unique_ptr<wchar_t> name = filename.ToWideStr(); switch (tt) { case DDS: { hr = CreateDDSTextureFromFile(device, name.get(), (ID3D11Resource **)texture, NULL); } break; //case TGA: case PNG: { hr = CreateWICTextureFromFile(device, name.get(), (ID3D11Resource **)texture, NULL); } break; } //if(SUCCEEDED(D3DX11CreateTextureFromFile(device, file.c_str(), NULL, NULL, (ID3D11Resource **)texture, NULL))) if(SUCCEEDED(hr)) { // Load the texture and store it GetTexture(filename, tt); D3D11_TEXTURE2D_DESC desc; (*texture)->GetDesc(&desc); // To keep it simple, we limit the textures we load to RGBA 8bits per channel if(desc.Format != DXGI_FORMAT_R8G8B8A8_UNORM) { OutputDebugStringA( "We want to read a simple RGBA texture 8 bits per channel but the required texture has a different format." ); return false; } desc.Usage = D3D11_USAGE_STAGING; desc.BindFlags = 0; desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ; if (device->CreateTexture2D(&desc, NULL, &tempTexture) != S_OK) return false; immediateContext->CopyResource(tempTexture, *texture); D3D11_MAPPED_SUBRESOURCE mappedResource; if (immediateContext->Map(tempTexture, 0, D3D11_MAP_READ, 0, &mappedResource) != S_OK) return false; textureDataSize = mappedResource.RowPitch * desc.Height; if(srcTextureData) delete [] srcTextureData; srcTextureData = new byte[textureDataSize]; memcpy(srcTextureData, mappedResource.pData, textureDataSize); immediateContext->Unmap(tempTexture, 0); return true; } else return false; }