//================================================================================================================
void CreateGameDirectory::CopyFolder(string folderName, string newPath)
{
	char myPath[_MAX_PATH + 1];
	GetModuleFileName(NULL, myPath, _MAX_PATH);
	BetterString bs(myPath);
	bs = bs.Strip("Debug\\ZShadeSandbox.exe");
	BetterString path = bs + "\\bin\\" + folderName;
	string folder_path = string(path.CStringBuffer());
	string new_folder_path = newPath;
	char* in_path = new char[strlen(folder_path.c_str()) + 1];
	strcpy_s(in_path, strlen(folder_path.c_str()) + 1, folder_path.c_str());
	char* out_path = new char[strlen(new_folder_path.c_str()) + 1];
	strcpy_s(out_path, strlen(new_folder_path.c_str()) + 1, new_folder_path.c_str());
	CopyAllFiles(in_path, out_path, "");
}
//===============================================================================================================================
void TextureManager::WriteToFile(BetterString filename, BetterString textureName)
{
    // Locate the texture
    map<string, ID3D11ShaderResourceView*>::iterator iter = m_pTextures.find(textureName.toString());
    if (iter != m_pTextures.end())
    {
        WriteToFile(filename, (*iter).second);
    }
}
//===============================================================================================================================
void TextureManager::WriteToFile(BetterString filename, ID3D11ShaderResourceView* textureSRV)
{
    string fileExt = CGlobal::GetFileExt(filename);

    if (fileExt == "dds")
    {
        unique_ptr<wchar_t> name = filename.ToWideStr();
        WriteDDSToFile(name.get(), textureSRV);
    }
    else if (fileExt == "tga")
    {
        unique_ptr<wchar_t> name = filename.ToWideStr();
        WriteTGAToFile(name.get(), textureSRV);
    }
    else if (fileExt == "png")
    {
        unique_ptr<wchar_t> name = filename.ToWideStr();
        WritePNGToFile(name.get(), textureSRV);
    }
}
//===============================================================================================================================
bool TextureManager::Exists(BetterString filename, D3D_VERSION d3d)
{
	if (d3d == DIRECTX10)
	{
		//map< string, ID3D10ShaderResourceView* >::iterator texture_it = m_pTextures.find(filename.toString());
		
		//if (texture_it != m_pTextureData.end())
		//	return true;
		//else
		//	return false;
	}
	else if (d3d == DIRECTX11)
	{
		map< string, ID3D11ShaderResourceView* >::iterator texture_it = m_pTextures.find(filename.toString());
		
		if (texture_it != m_pTextures.end())
			return true;
		else
			return false;
	}
	
	return false;
}
//=================================================================================================================
HRESULT ShaderCompiler::Compile(D3D* d3d, BetterString filename, BetterString shaderFuncName, int type, BetterString macroName, bool loadPrecompiledShader)
{
	// Compiling Shaders with D3DCompileFromFile
	//Google: visual studio 2013 hlsl shader compiling
	//http://msdn.microsoft.com/en-us/library/windows/desktop/hh968107(v=vs.85).aspx
	//http://stackoverflow.com/questions/10759300/how-do-i-use-shader-model-5-0-compiled-shaders-in-visual-studio-11
	/*
		Here "PixelShader.cso" is the precompiled hlsl shader generated by Visual Studio 11 from a .hlsl file in the project.
		The compiled .cso file is usually moved to the Projects/ProjectName/Debug folder by default.
		As a result it must be cut and paste into the same directory as your source code before using.
		Mind you this setting can be changed by right-clicking the HLSL file while inside Visual Studio 11 and
		editing the Output Settings. By default its: $(OutDir)%(Filename).cso, change it to: $(Directory)%(Filename).cso
	*/
	
	//Google: creating a cso file in DirectX11.1
	//http://stackoverflow.com/questions/5020204/loading-a-precompiled-hlsl-shader-into-memory-for-use-with-createpixelshader
	
	BetterString base = "..\\Framework\\Shaders\\";
	filename = base + filename;

	unique_ptr<wchar_t> name = filename.ToWideStr();

	HRESULT hr;
	ID3DBlob* blob = nullptr;
	ID3DBlob* errorBlob = nullptr;
	
    UINT flags = D3DCOMPILE_ENABLE_STRICTNESS;
#if defined( DEBUG ) || defined( _DEBUG )
    flags |= D3DCOMPILE_DEBUG;
#endif

	ShaderMacros* macros = 0;
	map<string, ShaderMacros*>::iterator it = m_ShaderMacros.find(macroName);
	if (it != m_ShaderMacros.end())
		macros = (*it).second;

	switch (type)
	{
		case EShaderTypes::ST_VERTEX:
		{
			VertexShader* vs = new VertexShader();
			LPCSTR profile = "vs_5_0";
			
			blob = Compile(name.get(), shaderFuncName, profile, flags, errorBlob, macros, loadPrecompiledShader);
			if (blob == nullptr)
			{
				OutputShaderErrorMessage(errorBlob, NULL, shaderFuncName, filename);
				exit(0);
			}
			
			hr = d3d->GetDevice11()->CreateVertexShader(blob->GetBufferPointer(), blob->GetBufferSize(), nullptr, &vs->mShader);
			if( FAILED(hr) )
			{
				OutputShaderErrorMessage(errorBlob, NULL, shaderFuncName, filename);
				exit(0);
			}
			
			vs->mBlobData = blob;
			vs->mName = shaderFuncName;
			
#if defined(DEBUG) || defined(PROFILE)
			if ( SUCCEEDED(hr) )
			{
				vs->mShader->SetPrivateData( WKPDID_D3DDebugObjectName, lstrlenA(shaderFuncName), shaderFuncName );
			}
#endif
			//Add the vertex shader to the list of shaders
			m_Shaders.push_back(vs);
		}
		break;
		case EShaderTypes::ST_HULL:
		{
			HullShader* hs = new HullShader();
			LPCSTR profile = "hs_5_0";
			
			blob = Compile(name.get(), shaderFuncName, profile, flags, errorBlob, macros, loadPrecompiledShader);
			if (blob == nullptr)
			{
				OutputShaderErrorMessage(errorBlob, NULL, shaderFuncName, filename);
				exit(0);
			}
			
			hr = d3d->GetDevice11()->CreateHullShader(blob->GetBufferPointer(), blob->GetBufferSize(), nullptr, &hs->mShader);
			if (FAILED(hr))
			{
				OutputShaderErrorMessage(errorBlob, NULL, shaderFuncName, filename);
				exit(0);
			}
			
			hs->mBlobData = blob;
			hs->mName = shaderFuncName;
			
#if defined(DEBUG) || defined(PROFILE)
			if (SUCCEEDED(hr))
			{
				hs->mShader->SetPrivateData(WKPDID_D3DDebugObjectName, lstrlenA(shaderFuncName), shaderFuncName);
			}
#endif
			
			//Add the hull shader to the list of shaders
			m_Shaders.push_back(hs);
		}
		break;
		case EShaderTypes::ST_DOMAIN:
		{
			DomainShader* ds = new DomainShader();
			LPCSTR profile = "ds_5_0";
			
			blob = Compile(name.get(), shaderFuncName, profile, flags, errorBlob, macros, loadPrecompiledShader);
			if (blob == nullptr)
			{
				OutputShaderErrorMessage(errorBlob, NULL, shaderFuncName, filename);
				exit(0);
			}
			
			hr = d3d->GetDevice11()->CreateDomainShader(blob->GetBufferPointer(), blob->GetBufferSize(), nullptr, &ds->mShader);
			if (FAILED(hr))
			{
				OutputShaderErrorMessage(errorBlob, NULL, shaderFuncName, filename);
				exit(0);
			}
			
			ds->mBlobData = blob;
			ds->mName = shaderFuncName;
			
#if defined(DEBUG) || defined(PROFILE)
			if (SUCCEEDED(hr))
			{
				ds->mShader->SetPrivateData(WKPDID_D3DDebugObjectName, lstrlenA(shaderFuncName), shaderFuncName);
			}
#endif
			
			//Add the domain shader to the list of shaders
			m_Shaders.push_back(ds);
		}
		break;
		case EShaderTypes::ST_PIXEL:
		{
			PixelShader* ps = new PixelShader();
			LPCSTR profile = "ps_5_0";
			
			blob = Compile(name.get(), shaderFuncName, profile, flags, errorBlob, macros, loadPrecompiledShader);
			if (blob == nullptr)
			{
				OutputShaderErrorMessage(errorBlob, NULL, shaderFuncName, filename);
				exit(0);
			}

			hr = d3d->GetDevice11()->CreatePixelShader(blob->GetBufferPointer(), blob->GetBufferSize(), nullptr, &ps->mShader);
			if (FAILED(hr))
			{
				OutputShaderErrorMessage(errorBlob, NULL, shaderFuncName, filename);
				exit(0);
			}

			ps->mBlobData = blob;
			ps->mName = shaderFuncName;

#if defined(DEBUG) || defined(PROFILE)
			if (SUCCEEDED(hr))
			{
				ps->mShader->SetPrivateData(WKPDID_D3DDebugObjectName, lstrlenA(shaderFuncName), shaderFuncName);
			}
#endif
			
			//Add the pixel shader to the list of shaders
			m_Shaders.push_back(ps);
		}
		break;
		case EShaderTypes::ST_GEOMETRY:
		{
			GeometryShader* gs = new GeometryShader();
			LPCSTR profile = "gs_5_0";
			
			blob = Compile(name.get(), shaderFuncName, profile, flags, errorBlob, macros, loadPrecompiledShader);
			if (blob == nullptr)
			{
				OutputShaderErrorMessage(errorBlob, NULL, shaderFuncName, filename);
				exit(0);
			}

			hr = d3d->GetDevice11()->CreateGeometryShader(blob->GetBufferPointer(), blob->GetBufferSize(), nullptr, &gs->mShader);
			if (FAILED(hr))
			{
				OutputShaderErrorMessage(errorBlob, NULL, shaderFuncName, filename);
				exit(0);
			}

			gs->mBlobData = blob;
			gs->mName = shaderFuncName;

#if defined(DEBUG) || defined(PROFILE)
			if (SUCCEEDED(hr))
			{
				gs->mShader->SetPrivateData(WKPDID_D3DDebugObjectName, lstrlenA(shaderFuncName), shaderFuncName);
			}
#endif
			
			//Add the geometry shader to the list of shaders
			m_Shaders.push_back(gs);
		}
		break;
		case EShaderTypes::ST_COMPUTE:
		{
			ComputeShader* cs = new ComputeShader();
			LPCSTR profile = "cs_5_0";
			
			blob = Compile(name.get(), shaderFuncName, profile, flags, errorBlob, macros, loadPrecompiledShader);
			if (blob == nullptr)
			{
				OutputShaderErrorMessage(errorBlob, NULL, shaderFuncName, filename);
				exit(0);
			}

			hr = d3d->GetDevice11()->CreateComputeShader(blob->GetBufferPointer(), blob->GetBufferSize(), nullptr, &cs->mShader);
			if (FAILED(hr))
			{
				OutputShaderErrorMessage(errorBlob, NULL, shaderFuncName, filename);
				exit(0);
			}

			cs->mBlobData = blob;
			cs->mName = shaderFuncName;

#if defined(DEBUG) || defined(PROFILE)
			if (SUCCEEDED(hr))
			{
				cs->mShader->SetPrivateData(WKPDID_D3DDebugObjectName, lstrlenA(shaderFuncName), shaderFuncName);
			}
#endif
			
			//Add the compute shader to the list of shaders
			m_Shaders.push_back(cs);
		}
		break;
		default:
		{
			ZShadeMessageCenter::MsgBoxError(NULL, "ShaderCompiler: ZShadeSandboxShader::Shader type not defined !!!");
			exit(0);
		}
		break;
	}
	
	return S_OK;
}
//===============================================================================================================================
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;
}
Example #7
0
//===================================================================================================================
bool Heightmap::LoadElevation(string heightmap)
{
	//Check the extention of the file
	BetterString hmap = heightmap;
	BetterString ext = hmap.Strip('.', hmap.size());
	//Not a valid script
	if (ext != "bmp")
	{
		if (ext != "raw")
		{
			return false;
		}
	}

	switch (m_ext)
	{
		case BMP:
		{
			#pragma region "Load BMP"
			FILE* file_ptr;
			int error;
			unsigned int count;
			BITMAPFILEHEADER bitmapFileHeader;
			BITMAPINFOHEADER bitmapInfoHeader;
			int imageSize, i, j, k, index;
			unsigned char* bitmapImage;
			unsigned char height;

			//Open the heightmap file in binary
			error = fopen_s(&file_ptr, heightmap.c_str(), "rb");

			if (error != 0) return false;

			//Read in the file header
			count = fread(&bitmapFileHeader, sizeof(BITMAPFILEHEADER), 1, file_ptr);

			if (count != 1) return false;

			//Read in the bitmap info header
			count = fread(&bitmapInfoHeader, sizeof(BITMAPINFOHEADER), 1, file_ptr);

			if (count != 1) return false;

			//Stoer the size of the heightmap
			m_heightmap_width = bitmapInfoHeader.biWidth;
			m_heightmap_height = bitmapInfoHeader.biHeight;

			//Calculate the size of the bitmap image data
			imageSize = m_heightmap_width * m_heightmap_height * 3;

			//Allocate memory for the bitmap image data
			bitmapImage = new unsigned char[imageSize];

			if (!bitmapImage) return false;

			//Move to the beginning of the bitmap data
			fseek(file_ptr, bitmapFileHeader.bfOffBits, SEEK_SET);

			//Read in the bitmap image data
			count = fread(bitmapImage, 1, imageSize, file_ptr);

			if (count != imageSize) return false;

			//Close the file
			error = fclose(file_ptr);

			if (error != 0) return false;

			//Create the structure to hold the raw height data
			//m_height_data = new HEIGHT_DATA[m_heightmap_width * m_heightmap_height];
	
			m_height_data = new float*[m_heightmap_height];
			for (i = 0; i < m_heightmap_height; i++)
			{
				m_height_data[i] = new float[m_heightmap_width];
			}

			if (!m_height_data) return false;

			//Initialize the position in the image data buffer
			k = 0;

			//Read the image data into the heightmap
			for (j = 0; j < m_heightmap_height; j++)
			{
				for (i = 0; i < m_heightmap_width; i++)
				{
					height = (bitmapImage[k] / 255.0f) * m_height_scale;

					m_height_data[j][i] = (float)height;

					k += 3;
				}
			}

			//Release the bitmap image data
			delete[] bitmapImage;
			bitmapImage = 0;

			return true;
			#pragma endregion
		}
		break;
		case RAW:
		{
			#pragma region "Load RAW"
			vector<unsigned char> in (m_heightmap_width * m_heightmap_height);

			//Open the file
			ifstream inFile(heightmap, ios_base::binary);
			
			if (inFile)
			{
				//Read the RAW bytes
				inFile.read((char*)&in[0], (streamsize)in.size());

				//Done with file
				inFile.close();
			}

			//Copy the array data into a float array and scale it.
			m_heightmap.resize(m_heightmap_width * m_heightmap_height, 0);
			for (UINT i = 0; i < m_heightmap_width * m_heightmap_height; ++i)
			{
				m_heightmap[i] = (in[i] / 255.0f) * m_height_scale;
			}
			#pragma endregion
		}
		break;
		default: break;//Do not support anything else currently
	}
}
Example #8
0
//===============================================================================================================================
void FBXLoader::LoadMaterialTexture(FbxSurfaceMaterial* inMaterial, ZShadeSandboxLighting::ShaderMaterial*& ioMaterial)
{
	uint32 textureIndex = 0;
	FbxProperty property;
	
	FBXSDK_FOR_EACH_TEXTURE(textureIndex)
	{
		property = inMaterial->FindProperty(FbxLayerElement::sTextureChannelNames[textureIndex]);
		if (property.IsValid())
		{
			uint32 textureCount = property.GetSrcObjectCount<FbxTexture>();
			for (uint32 i = 0; i < textureCount; ++i)
			{
				FbxLayeredTexture* layeredTexture = property.GetSrcObject<FbxLayeredTexture>(i);
				if(layeredTexture)
				{
					throw std::exception("Layered Texture is currently unsupported\n");
				}
				else
				{
					FbxTexture* texture = property.GetSrcObject<FbxTexture>(i);
					if (texture)
					{
						std::string textureType = property.GetNameAsCStr();
						FbxFileTexture* fileTexture = FbxCast<FbxFileTexture>(texture);

						if (fileTexture)
						{
							string str_filename(fileTexture->GetFileName());
							std::size_t index = str_filename.find_last_of('/\\');
							if (index != string::npos)
							{
								BetterString str(fileTexture->GetFileName());
								int dot_index = str.get_index('.');
								BetterString pathName = str.substring(index + 1, dot_index);
								BetterString ext = str.substring(dot_index + 1);
								BetterString filename = pathName + "." + ext;
								str_filename = filename.toString();
							}

							if (textureType == "DiffuseColor")
							{
								ioMaterial->sDiffuseTextureName = str_filename;
								ioMaterial->bHasDiffuseTexture = true;
							}
							else if (textureType == "SpecularColor")
							{
								ioMaterial->sSpecularTextureName = str_filename;
								ioMaterial->bHasSpecularTexture = true;
							}
							else if (textureType == "Bump")
							{
								ioMaterial->sNormalMapTextureName = str_filename;
								ioMaterial->bHasNormalMapTexture = true;
							}
						}
					}
				}
			}
		}
	}
	
	ioMaterial->SetD3D(m_pD3DSystem);
	
	bool addToMM = false;
	
	if (ioMaterial->bHasDiffuseTexture)
	{
		ZShadeSandboxLighting::ShaderMaterial* material;
		if (material = MaterialManager::Instance()->GetMaterial(ioMaterial->sMaterialName))
		{
			// The texture has already been loaded
			ioMaterial->SetMaterialDiffuseTexture(material->DiffuseTexture());
		}
		else
		{
			// Need to load new texture
			ioMaterial->AddDiffuseTexture(m_pGD3D->m_textures_path, ioMaterial->sDiffuseTextureName);
			
			addToMM = true;
		}
	}
	
	if (ioMaterial->bHasSpecularTexture)
	{
		ZShadeSandboxLighting::ShaderMaterial* material;
		if (material = MaterialManager::Instance()->GetMaterial(ioMaterial->sMaterialName))
		{
			// The texture has already been loaded
			ioMaterial->SetMaterialSpecularTexture(material->SpecularTexture());
		}
		else
		{
			// Need to load new texture
			ioMaterial->AddDiffuseTexture(m_pGD3D->m_textures_path, ioMaterial->sSpecularTextureName);
			
			addToMM = true;
		}
	}
	
	if (ioMaterial->bHasNormalMapTexture)
	{
		ZShadeSandboxLighting::ShaderMaterial* material;
		if (material = MaterialManager::Instance()->GetMaterial(ioMaterial->sMaterialName))
		{
			// The texture has already been loaded
			ioMaterial->SetMaterialNormalMapTexture(material->NormalMapTexture());
		}
		else
		{
			// Need to load new texture
			ioMaterial->AddDiffuseTexture(m_pGD3D->m_textures_path, ioMaterial->sNormalMapTextureName);
			
			addToMM = true;
		}
	}
	
	if (addToMM)
	{
		MaterialManager::Instance()->Add(ioMaterial);
	}
}