void Scene::LoadFromXFile(string file, IDirect3DDevice9 *device) { assert(device); ID3DXBuffer *material = nullptr; DWORD num_material = 0; ID3DXMesh *mesh = nullptr; HRESULT res = D3DXLoadMeshFromX(file.c_str(), // pFilename D3DXMESH_DYNAMIC, // Options device, // pD3DDevice nullptr, // ppAdjacency &material, // ppMaterials nullptr, // ppEffectInstances &num_material, // pNumMaterials &mesh); // ppMesh if (FAILED(res)) { Logger::GtLogError("load mesh from X file failed:%s", file.c_str()); return; } assert(num_material == 1); D3DXMATERIAL *mat = static_cast<D3DXMATERIAL *>(material->GetBufferPointer()); material_.ambient.r = mat->MatD3D.Ambient.r; material_.ambient.g = mat->MatD3D.Ambient.g; material_.ambient.b = mat->MatD3D.Ambient.b; material_.ambient.a = mat->MatD3D.Ambient.a; material_.diffuse.r = mat->MatD3D.Diffuse.r; material_.diffuse.g = mat->MatD3D.Diffuse.g; material_.diffuse.b = mat->MatD3D.Diffuse.b; material_.diffuse.a = mat->MatD3D.Diffuse.a; material_.specular.r = mat->MatD3D.Specular.r; material_.specular.g = mat->MatD3D.Specular.g; material_.specular.b = mat->MatD3D.Specular.b; material_.specular.a = mat->MatD3D.Specular.a; material_.emissive.r = mat->MatD3D.Emissive.r; material_.emissive.g = mat->MatD3D.Emissive.g; material_.emissive.b = mat->MatD3D.Emissive.b; material_.emissive.a = mat->MatD3D.Emissive.a; material_.power = mat->MatD3D.Power; bool ret = texture_.Load(mat->pTextureFilename, device); assert(ret); material->Release(); DWORD num_vertex = mesh->GetNumVertices(); IDirect3DVertexBuffer9 *vertex_buffer = nullptr; res = mesh->GetVertexBuffer(&vertex_buffer); assert(SUCCEEDED(res)); uint8 *vertex_data = nullptr; res = vertex_buffer->Lock(0, 0, reinterpret_cast<void **>(&vertex_data), D3DLOCK_READONLY); assert(SUCCEEDED(res)); D3DVERTEXELEMENT9 vertex_elements[MAX_FVF_DECL_SIZE] = {0}; res = mesh->GetDeclaration(vertex_elements); assert(SUCCEEDED(res)); int offset_pos = 0; int offset_nor = 0; int offset_tex = 0; int vertex_size = mesh->GetNumBytesPerVertex(); for (int i = 0; i < MAX_FVF_DECL_SIZE; ++i) { if (vertex_elements[i].Type == D3DDECLTYPE_UNUSED) break; if (vertex_elements[i].Usage == D3DDECLUSAGE_POSITION) { offset_pos = vertex_elements[i].Offset; } if (vertex_elements[i].Usage == D3DDECLUSAGE_NORMAL) { offset_nor = vertex_elements[i].Offset; } if (vertex_elements[i].Usage == D3DDECLUSAGE_TEXCOORD) { offset_tex = vertex_elements[i].Offset; } } Primitive verteies(num_vertex, nullptr, nullptr); for (int i = 0; i < num_vertex; ++i) { verteies.positions[i] = *reinterpret_cast<Vector3 *>(vertex_data + vertex_size * i + offset_pos); verteies.positions[i].Display(); verteies.normals[i] = *reinterpret_cast<Vector3 *>(vertex_data + vertex_size * i + offset_nor); verteies.normals[i].Display(); verteies.uvs[i] = *reinterpret_cast<Vector2 *>(vertex_data + vertex_size * i + offset_tex); verteies.uvs[i].Display(); } primitive_ = verteies; vertex_buffer->Unlock(); vertex_buffer->Release(); }
SMAA::SMAA(IDirect3DDevice9 *device, int width, int height, Preset preset, const ExternalStorage &storage) : Effect(device), threshold(0.1f), maxSearchSteps(8), width(width), height(height) { HRESULT hr; // Setup the defines for compiling the effect. vector<D3DXMACRO> defines; stringstream s; // Setup pixel size macro s << "float2(1.0 / " << width << ", 1.0 / " << height << ")"; string pixelSizeText = s.str(); D3DXMACRO pixelSizeMacro = { "SMAA_PIXEL_SIZE", pixelSizeText.c_str() }; defines.push_back(pixelSizeMacro); // Setup preset macro D3DXMACRO presetMacros[] = { { "SMAA_PRESET_LOW", "1" }, { "SMAA_PRESET_MEDIUM", "1" }, { "SMAA_PRESET_HIGH", "1" }, { "SMAA_PRESET_ULTRA", "1" }, { "SMAA_PRESET_CUSTOM", "1" } }; defines.push_back(presetMacros[int(preset)]); D3DXMACRO null = { NULL, NULL }; defines.push_back(null); // Setup the flags for the effect. DWORD flags = D3DXFX_NOT_CLONEABLE | D3DXSHADER_OPTIMIZATION_LEVEL3; #ifdef D3DXFX_LARGEADDRESS_HANDLE flags |= D3DXFX_LARGEADDRESSAWARE; #endif // Load effect from file SDLOG(0, "SMAA load\n"); ID3DXBuffer* errors; hr = D3DXCreateEffectFromFile(device, GetDirectoryFile("dsfix\\SMAA.fx"), &defines.front(), NULL, flags, NULL, &effect, &errors); if(hr != D3D_OK) SDLOG(0, "ERRORS:\n %s\n", errors->GetBufferPointer()); // If storage for the edges is not specified we will create it. if (storage.edgeTex != NULL && storage.edgeSurface != NULL) { edgeTex = storage.edgeTex; edgeSurface = storage.edgeSurface; releaseEdgeResources = false; } else { V(device->CreateTexture(width, height, 1, D3DUSAGE_RENDERTARGET, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &edgeTex, NULL)); V(edgeTex->GetSurfaceLevel(0, &edgeSurface)); releaseEdgeResources = true; } // Same for blending weights. if (storage.blendTex != NULL && storage.blendSurface != NULL) { blendTex = storage.blendTex; blendSurface = storage.blendSurface; releaseBlendResources = false; } else { V(device->CreateTexture(width, height, 1, D3DUSAGE_RENDERTARGET, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &blendTex, NULL)); V(blendTex->GetSurfaceLevel(0, &blendSurface)); releaseBlendResources = true; } // Load the precomputed textures. loadAreaTex(); loadSearchTex(); // Create some handles for techniques and variables. thresholdHandle = effect->GetParameterByName(NULL, "threshold"); maxSearchStepsHandle = effect->GetParameterByName(NULL, "maxSearchSteps"); areaTexHandle = effect->GetParameterByName(NULL, "areaTex2D"); searchTexHandle = effect->GetParameterByName(NULL, "searchTex2D"); colorTexHandle = effect->GetParameterByName(NULL, "colorTex2D"); depthTexHandle = effect->GetParameterByName(NULL, "depthTex2D"); edgesTexHandle = effect->GetParameterByName(NULL, "edgesTex2D"); blendTexHandle = effect->GetParameterByName(NULL, "blendTex2D"); lumaEdgeDetectionHandle = effect->GetTechniqueByName("LumaEdgeDetection"); colorEdgeDetectionHandle = effect->GetTechniqueByName("ColorEdgeDetection"); depthEdgeDetectionHandle = effect->GetTechniqueByName("DepthEdgeDetection"); blendWeightCalculationHandle = effect->GetTechniqueByName("BlendWeightCalculation"); neighborhoodBlendingHandle = effect->GetTechniqueByName("NeighborhoodBlending"); }
bool CShaderHLSL::Create(P3D::sShaderDesc &desc) { const char *pData; ULONG fsize; IFileSystem* pFS = CRenderer::mEngine()->mFilesystem(); wchar path[P3DMAX_PATH]; wsprintf(path, P3DMAX_PATH-1, _W("shaders/%s.rshader"), desc.ShaderFile.Get()); FSFILE *fp = pFS->Load(path, (BYTE *&)pData, fsize, true); if (!fp) { CON(MSG_ERR, _W("Can't open %s.hlsl shader file from data/shaders directory!"), desc.ShaderFile.Get()); return false; } ID3DXBuffer *pShaderBlob = NULL; ID3DXBuffer *pErrors = NULL; DWORD flags = D3DXSHADER_DEBUG; //D3DXSHADER_OPTIMIZATION_LEVEL3 char profile[128]; switch(desc.ShaderType) { case SHADERTYPE_VERTEX_SHADER: strcpy(profile, D3DXGetVertexShaderProfile(g_pD3ddev)); break; case SHADERTYPE_PIXEL_SHADER: strcpy(profile, D3DXGetPixelShaderProfile(g_pD3ddev)); break; case SHADERTYPE_GEOMETRY_SHADER: CON(MSG_ERR, _W("DX9 does not support geometry shaders.")); return false; default: CON(MSG_ERR, _W("Chader creation failed. No apropriate ShaderType given.")); return false; } CIncludeHandler includeHandler; D3DXMACRO Shader_Macros[] = { { "DX9", NULL }, { "SM3", NULL }, NULL }; if(FAILED(D3DXCompileShader( pData, fsize, Shader_Macros, &includeHandler, _W2A(desc.EntryFunction.Get()), profile, flags, &pShaderBlob, &pErrors, &m_pConstTable ))) { if(pErrors) CON(MSG_ERR, _W("%s"), _A2W((char*)pErrors->GetBufferPointer())); else CON(MSG_ERR, _W("Error description not given")); CON(MSG_ERR, _W("Shader %s could not be compiled"), desc.ShaderFile.Get()); SAFE_RELEASE(pErrors); return false; } pFS->UnLoad(fp, (BYTE *)pData); //save to cache fp = pFS->Open(_W("cache/shaders/hlsl"), _W("wb")); const char* cs = (const char*)pShaderBlob->GetBufferPointer(); pFS->Write(cs, 1, pShaderBlob->GetBufferSize(), fp); pFS->Close(fp); bool shaderCreated = false; switch(desc.ShaderType) { case SHADERTYPE_VERTEX_SHADER: shaderCreated = SUCCEEDED(g_pD3ddev->CreateVertexShader((const DWORD*)pShaderBlob->GetBufferPointer(), &m_pVS)); break; case SHADERTYPE_PIXEL_SHADER: shaderCreated = SUCCEEDED(g_pD3ddev->CreatePixelShader((const DWORD*)pShaderBlob->GetBufferPointer(), &m_pPS)); break; } if(!shaderCreated) { CON(MSG_ERR, _W("Shader creation error")); return false; } //set constant to their default values m_pConstTable->SetDefaults(g_pD3ddev); //create vertex declaration if(desc.ShaderType == SHADERTYPE_VERTEX_SHADER) m_pVertDecl = new CVertexDeclaration(CRenderer::cGraphicsManager()->GetVertexDescByID(desc.VertexDescID), pShaderBlob); SAFE_RELEASE(pShaderBlob); m_desc = desc; CON(MSG_INFO, _W("Shader '%s' created"), desc.ShaderFile); return true; }
// // Framework functions // bool Setup() { HRESULT hr = 0; // // Load the XFile data. // ID3DXBuffer* adjBuffer = 0; ID3DXBuffer* mtrlBuffer = 0; DWORD numMtrls = 0; hr = D3DXLoadMeshFromX( "bigship1.x", D3DXMESH_MANAGED, Device, &adjBuffer, &mtrlBuffer, 0, &numMtrls, &SourceMesh); if(FAILED(hr)) { ::MessageBox(0, "D3DXLoadMeshFromX() - FAILED", 0, 0); return false; } // // Extract the materials, load textures. // if( mtrlBuffer != 0 && numMtrls != 0 ) { D3DXMATERIAL* mtrls = (D3DXMATERIAL*)mtrlBuffer->GetBufferPointer(); for(int i = 0; i < numMtrls; i++) { // the MatD3D property doesn't have an ambient value set // when its loaded, so set it now: mtrls[i].MatD3D.Ambient = mtrls[i].MatD3D.Diffuse; // save the ith material Mtrls.push_back( mtrls[i].MatD3D ); // check if the ith material has an associative texture if( mtrls[i].pTextureFilename != 0 ) { // yes, load the texture for the ith subset IDirect3DTexture9* tex = 0; D3DXCreateTextureFromFile( Device, mtrls[i].pTextureFilename, &tex); // save the loaded texture Textures.push_back( tex ); } else { // no texture for the ith subset Textures.push_back( 0 ); } } } d3d::Release<ID3DXBuffer*>(mtrlBuffer); // done w/ buffer // // Optimize the mesh. // hr = SourceMesh->OptimizeInplace( D3DXMESHOPT_ATTRSORT | D3DXMESHOPT_COMPACT | D3DXMESHOPT_VERTEXCACHE, (DWORD*)adjBuffer->GetBufferPointer(), (DWORD*)adjBuffer->GetBufferPointer(), // new adjacency info 0, 0); if(FAILED(hr)) { ::MessageBox(0, "OptimizeInplace() - FAILED", 0, 0); d3d::Release<ID3DXBuffer*>(adjBuffer); // free return false; } // // Generate the progressive mesh. // hr = D3DXGeneratePMesh( SourceMesh, (DWORD*)adjBuffer->GetBufferPointer(), // adjacency 0, // default vertex attribute weights 0, // default vertex weights 1, // simplify as low as possible D3DXMESHSIMP_FACE, // simplify by face count &PMesh); d3d::Release<ID3DXMesh*>(SourceMesh); // done w/ source mesh d3d::Release<ID3DXBuffer*>(adjBuffer); // done w/ buffer if(FAILED(hr)) { ::MessageBox(0, "D3DXGeneratePMesh() - FAILED", 0, 0); return false; } // set to original detail DWORD maxFaces = PMesh->GetMaxFaces(); PMesh->SetNumFaces(maxFaces); // // Set texture filters. // Device->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR); Device->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR); Device->SetSamplerState(0, D3DSAMP_MIPFILTER, D3DTEXF_POINT); // // Set Lights. // D3DXVECTOR3 dir(1.0f, -1.0f, 1.0f); D3DXCOLOR col(1.0f, 1.0f, 1.0f, 1.0f); D3DLIGHT9 light = d3d::InitDirectionalLight(&dir, &col); Device->SetLight(0, &light); Device->LightEnable(0, true); Device->SetRenderState(D3DRS_NORMALIZENORMALS, true); Device->SetRenderState(D3DRS_SPECULARENABLE, true); // // Set camera. // D3DXVECTOR3 pos(-8.0f, 4.0f, -12.0f); D3DXVECTOR3 target(0.0f, 0.0f, 0.0f); D3DXVECTOR3 up(0.0f, 1.0f, 0.0f); //pos/=2; D3DXMATRIX V; D3DXMatrixLookAtLH( &V, &pos, &target, &up); Device->SetTransform(D3DTS_VIEW, &V); // // Set projection matrix. // D3DXMATRIX proj; D3DXMatrixPerspectiveFovLH( &proj, D3DX_PI * 0.5f, // 90 - degree (float)Width / (float)Height, 1.0f, 1000.0f); Device->SetTransform(D3DTS_PROJECTION, &proj); return true; }
//-------------------------------------------------------------------------------------- HRESULT Effect9::FromSource( IDirect3DDevice9* pDevice, const SourceInfo& sf, const D3DXMACRO* pDefines, ID3DXInclude* pInclude, DWORD flags, Effect9** ppEffectOut ) { HRESULT hr; hr = S_OK; if( NULL == ppEffectOut ) return E_INVALIDARG; // Clear the output parameter *ppEffectOut = NULL; // Attempt to create the D3DXEffect ID3DXEffect* pD3DXEffect = NULL; ID3DXBuffer* pErrors = NULL; if(sf.GetSourceType() == SOURCEINFO_RESOURCE) { hr = SASCreateEffectFromResource( pDevice, sf.GetResourceModule(), sf.GetResourceName(), sf.GetResourceType(), pDefines, pInclude, flags, NULL, &pD3DXEffect, &pErrors ); } else if(sf.GetSourceType() == SOURCEINFO_FILE) { hr = D3DXCreateEffectFromFile( pDevice, sf.GetFilePath(), pDefines, pInclude, flags, NULL, &pD3DXEffect, &pErrors ); if( hr == E_NOTIMPL) hr = D3DXCreateEffectFromFile( pDevice, sf.GetFilePath(), pDefines, pInclude, (flags | D3DXSHADER_USE_LEGACY_D3DX9_31_DLL), NULL, &pD3DXEffect, &pErrors ); } if( pErrors ) Sas::Host::OutAnsi( FAILED(hr)?LEVEL_ERROR:LEVEL_WARNING, "%s", (LPSTR)pErrors->GetBufferPointer() ); if( FAILED(hr) ) goto e_Exit; D3DXHANDLE technique = NULL; hr= pD3DXEffect->FindNextValidTechnique(NULL, &technique); if( FAILED(hr) ) { Sas::Host::Out( LEVEL_ERROR, L"No technique in the effect is valid on your hardware." ); goto e_Exit; } pD3DXEffect->SetTechnique(technique); // Now that we have a D3DXEffect we can create a Sas::Effect hr = FromD3DXEffect( pD3DXEffect, sf, ppEffectOut ); e_Exit: SAFE_RELEASE(pErrors); SAFE_RELEASE( pD3DXEffect ); if(SUCCEEDED(hr)) Sas::Host::Out( LEVEL_STATUS, L"Loading effect '%s'", sf.GetDescription() ); else Sas::Host::Out( LEVEL_ERROR, L"Could not load effect '%s'", sf.GetDescription() ); return hr; }
Bloom::Bloom(IDirect3DDevice9 *device, int width, int height, float cutoff, float strength, float dirtStrength) : Effect(device), width(width), height(height), cutoff(cutoff), strength(strength), dirtStrength(dirtStrength), steps(0), dumping(false) { // Setup the defines for compiling the effect vector<D3DXMACRO> defines; //string cutoffText = format("%lf", cutoff); //D3DXMACRO cutoffMacro = { "CUTOFF", cutoffText.c_str() }; //defines.push_back(cutoffMacro); //string strengthText = format("%lf", strength); //D3DXMACRO strengthMacro = { "STRENGTH", strengthText.c_str() }; //defines.push_back(strengthMacro); //string dirtStrengthText = format("%lf", dirtStrength); //D3DXMACRO dirtStrengthMacro = { "DIRT_STRENGTH", dirtStrengthText.c_str() }; //defines.push_back(dirtStrengthMacro); D3DXMACRO null = { NULL, NULL }; defines.push_back(null); DWORD flags = D3DXFX_NOT_CLONEABLE | D3DXSHADER_OPTIMIZATION_LEVEL3; // Load effect from file string shaderFn = getAssetFileName("bloom.fx"); SDLOG(0, "%s load\n", shaderFn.c_str()); ID3DXBuffer* errors; HRESULT hr = D3DXCreateEffectFromFile(device, shaderFn.c_str(), &defines.front(), NULL, flags, NULL, &effect, &errors); if(hr != D3D_OK) SDLOG(-1, "ERRORS compiling bloom.fx:\n %s\n", errors->GetBufferPointer()); // Load texture hr = D3DXCreateTextureFromFile(device, getAssetFileName("lensdirt.dds").c_str(), &dirtTexture); if(hr != D3D_OK) SDLOG(-1, "ERROR loading bloom texture lensdirt.dds\n"); // Create buffers int sWidth = width, sHeight = height; unsigned i = 0; while(max(sWidth,sHeight) > 1) { if(min(sWidth,sHeight) <= STEP_MINSIZE && sWidth != sHeight) { sWidth = STEP_MINSIZE; sHeight = STEP_MINSIZE; } else { sWidth /= 2; sHeight /= 2; } SDLOG(2, "Generating bloom buffer %2u - %4dx%4d\n", i, sWidth, sHeight); Size s = { sWidth, sHeight }; stepSizes.push_back(s); for(unsigned j=0; j<2; ++j) { stepBuffers[j].emplace_back(); stepBuffers[j][i] = RSManager::getRTMan().createTexture(sWidth, sHeight, D3DFMT_A16B16G16R16F); } ++i; } steps = i; // Get handles #define GETHANDLE(__name) \ __name##Handle = effect->GetParameterByName(NULL, #__name); \ if(__name##Handle == NULL) SDLOG(-1, "ERROR loading handle %s in Bloom effect\n", #__name); GETHANDLE(inputPixelMetrics) GETHANDLE(invSteps); GETHANDLE(sampleTex); GETHANDLE(passTex); GETHANDLE(dirtTex); GETHANDLE(avgTex); #undef GETHANDLE #define GETHANDLE(__name) \ __name##Handle = effect->GetTechniqueByName(#__name); \ if(__name##Handle == NULL) SDLOG(-1, "ERROR loading technique handle %s in Bloom effect\n", #__name); GETHANDLE(initialCutoffAndDownsample); GETHANDLE(gaussian); GETHANDLE(integrateUpwards); GETHANDLE(eyeAdaption); GETHANDLE(finalCompose); #undef GETHANDLE }
// // Framework functions // bool Setup() { HRESULT hr = 0; // // Init Scene. // D3DXVECTOR3 lightDirection(0.0f, 1.0f, 0.0f); TheTerrain = new Terrain(Device, "coastMountain64.raw", 64, 64, 6, 0.5f); TheTerrain->genTexture(&lightDirection); // // Set texture filters. // Device->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR); Device->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR); Device->SetSamplerState(0, D3DSAMP_MIPFILTER, D3DTEXF_LINEAR); // // Set Camera Position. // D3DXVECTOR3 pos(100.0f, 100.0f, -250.0f); TheCamera.setPosition(&pos); // // Create effect. // ID3DXBuffer* errorBuffer = 0; hr = D3DXCreateEffectFromFile( Device, "fog.fx", 0, // no preprocessor definitions 0, // no ID3DXInclude interface D3DXSHADER_DEBUG, // compile flags 0, // don't share parameters &FogEffect, &errorBuffer); // output any error messages if( errorBuffer ) { ::MessageBox(0, (char*)errorBuffer->GetBufferPointer(), 0, 0); d3d::Release<ID3DXBuffer*>(errorBuffer); } if(FAILED(hr)) { ::MessageBox(0, "D3DXCreateEffectFromFile() - FAILED", 0, 0); return false; } // // Save Frequently Accessed Parameter Handles // FogTechHandle = FogEffect->GetTechniqueByName("Fog"); // // Set Projection. // D3DXMATRIX P; D3DXMatrixPerspectiveFovLH( &P, D3DX_PI * 0.25f, // 45 - degree (float)Width / (float)Height, 1.0f, 1000.0f); Device->SetTransform(D3DTS_PROJECTION, &P); return true; }
void MyGame3DDevice::InitSceneEffectShader() { // load shader HRSRC hResource = ::FindResource( NULL, MAKEINTRESOURCE(IDR_PIXEL_SHADER2), RT_RCDATA ); HGLOBAL hResourceData = ::LoadResource( NULL, hResource ); LPVOID pData = ::LockResource( hResourceData ); ID3DXBuffer* errorBuffer = 0; HR( D3DXCreateEffect( pD3D9InstanceDevice, pData, ::SizeofResource( NULL, hResource ), 0, 0, 0, 0, &mFX, &errorBuffer ) ); if( errorBuffer ) { MyGameMessage( (char*)errorBuffer->GetBufferPointer() ); errorBuffer->Release(); return; } //initialize matrix in shader D3DXMATRIX worldMatrix; D3DXMatrixTranslation( &worldMatrix, -512.0f, -384.0f, 0 ); D3DXVECTOR3 position( 0.0f, 0.0f, 20.0f ); D3DXVECTOR3 targetPoint( 0.0f, 0.0f ,0.0f ); D3DXVECTOR3 upVector( 0.0f, -1.0f, 0.0f ); D3DXMATRIX viewMatrix; D3DXMatrixLookAtLH( &viewMatrix, &position, &targetPoint, &upVector ); D3DXMATRIX projMatrix; D3DXMatrixOrthoLH( &projMatrix, 1024.0f, 768.0f, -1009.0f, 5000.0f ); D3DXMatrixTranslation( &uiMoveMatrix, 0.0f, 0.0f, 0 ); mhUIWorldMatHandle = mFX->GetParameterByName( 0, worldMatName ); mhUIViewMatHandle = mFX->GetParameterByName( 0, viewMatName ); mhUIProjMatHandle = mFX->GetParameterByName( 0, projMatName ); mhUIMoveMatHandle = mFX->GetParameterByName( 0, moveMatName ); mhAlphaEnabled = mFX->GetParameterByName( 0, "alphaEnable" ); D3DXHANDLE mhTech = mFX->GetTechniqueByName( techniqueName ); mhTex = mFX->GetParameterByName( 0, "gTex" ); mFX->SetMatrix( mhUIWorldMatHandle, &worldMatrix ); mFX->SetMatrix( mhUIViewMatHandle, &viewMatrix ); mFX->SetMatrix( mhUIProjMatHandle, &projMatrix ); mFX->SetMatrix( mhUIMoveMatHandle, &uiMoveMatrix ); mFX->SetTechnique( mhTech ); HR(mFX->SetBool( mhAlphaEnabled, FALSE )); return; }
// // Framework functions // bool Setup() { HRESULT hr = 0; // // Create geometry. // D3DXCreateTeapot(Device, &Teapot, 0); // // Compile shader. // ID3DXBuffer* shader = 0; ID3DXBuffer* errorBuffer = 0; hr = D3DXCompileShaderFromFile( "transform.txt", 0, 0, "Main", // entry point function name "vs_1_1",// shader version to compile to D3DXSHADER_DEBUG, &shader, &errorBuffer, &TransformConstantTable); // output any error messages if( errorBuffer ) { ::MessageBox(0, (char*)errorBuffer->GetBufferPointer(), 0, 0); d3d::Release<ID3DXBuffer*>(errorBuffer); } if(FAILED(hr)) { ::MessageBox(0, "D3DXCreateEffectFromFile() - FAILED", 0, 0); return false; } hr = Device->CreateVertexShader( (DWORD*)shader->GetBufferPointer(), &TransformShader); if(FAILED(hr)) { ::MessageBox(0, "CreateVertexShader - FAILED", 0, 0); return false; } d3d::Release<ID3DXBuffer*>(shader); // // Get Handles. // TransformViewProjHandle = TransformConstantTable->GetConstantByName(0, "ViewProjMatrix"); // // Set shader constants: // TransformConstantTable->SetDefaults(Device); // // Set Projection Matrix. // D3DXMatrixPerspectiveFovLH( &ProjMatrix, D3DX_PI * 0.25f, (float)Width / (float)Height, 1.0f, 1000.0f); // // Set Misc. States. // Device->SetRenderState(D3DRS_FILLMODE, D3DFILL_WIREFRAME); return true; }
void cMesh::ParseXFileData(ID3DXFileData *pDataObj, sFrame *ParentFrame, char *TexturePath) { ID3DXFileData *pSubObj = NULL; ID3DXFileData *pSubData = NULL; IDirectXFileDataReference *pDataRef = NULL; GUID Type = GUID_NULL; char *Name = NULL; DWORD Size; sFrame *SubFrame = NULL; char Path[MAX_PATH]; sFrame *Frame = NULL; //D3DXMATRIX *FrameMatrix = NULL; sMesh *Mesh = NULL; ID3DXBuffer *MaterialBuffer = NULL; D3DXMATERIAL *Materials = NULL; ID3DXBuffer *Adjacency = NULL; DWORD *AdjacencyIn = NULL; DWORD *AdjacencyOut = NULL; DWORD i; BYTE **Ptr; // Get the template type if(FAILED(pDataObj->GetType((&Type)))) return; // Get the template name (if any) if(FAILED(pDataObj->GetName(NULL, &Size))) return; if(Size) { if((Name = new char[Size]) != NULL) pDataObj->GetName(Name, &Size); } // Give template a default name if none found if(Name == NULL) { if((Name = new char[9]) == NULL) return; strcpy(Name, "$NoName$"); } // Set sub frame SubFrame = ParentFrame; // Process the templates // Frame if(IsEqualGUID(Type, TID_D3DRMFrame)) { // Create a new frame structure Frame = new sFrame(); // Store the name Frame->m_Name = Name; Name = NULL; // Add to parent frame Frame->m_Parent = ParentFrame; Frame->m_Sibling = ParentFrame->m_Child; ParentFrame->m_Child = Frame; // Increase frame count m_NumFrames++; // Set sub frame parent SubFrame = Frame; } // Frame transformation matrix if(Type == TID_D3DRMFrameTransformMatrix) { BYTE** DataPtr = NULL; if(FAILED(pDataObj->Lock(&Size, (LPCVOID*)&DataPtr))) return; memcpy(&ParentFrame->m_matOriginal, (void*)DataPtr, Size); pDataObj->Unlock(); } // Mesh if(Type == TID_D3DRMMesh) { // See if mesh already loaded if(m_Meshes == NULL || m_Meshes->FindMesh(Name) == NULL) { // Create a new mesh structure Mesh = new sMesh(); // Store the name Mesh->m_Name = Name; Name = NULL; // Load mesh data if(FAILED(D3DXLoadSkinMeshFromXof(pDataObj, 0, m_Graphics->GetDeviceCOM(), &Adjacency, &MaterialBuffer, NULL, &Mesh->m_NumMaterials, &Mesh->m_SkinInfo, &Mesh->m_Mesh))) { delete Mesh; return; } // Calculate the bounding box and sphere if(SUCCEEDED(Mesh->m_Mesh->LockVertexBuffer(D3DLOCK_READONLY, (void**)&Ptr))) { D3DXComputeBoundingBox((D3DXVECTOR3*)Ptr, Mesh->m_Mesh->GetNumVertices(), Mesh->m_Mesh->GetNumBytesPerVertex(), &Mesh->m_Min, &Mesh->m_Max); D3DXComputeBoundingSphere((D3DXVECTOR3*)Ptr, Mesh->m_Mesh->GetNumVertices(), Mesh->m_Mesh->GetNumBytesPerVertex(), &D3DXVECTOR3(0.0f,0.0f,0.0f), &Mesh->m_Radius); Mesh->m_Mesh->UnlockVertexBuffer(); } // Store # of bones (if any) if(Mesh->m_SkinInfo) Mesh->m_NumBones = Mesh->m_SkinInfo->GetNumBones(); // Create a matching skinned mesh if bone exist if(Mesh->m_SkinInfo != NULL && Mesh->m_NumBones != 0) { if(FAILED(Mesh->m_Mesh->CloneMeshFVF(0, Mesh->m_Mesh->GetFVF(), m_Graphics->GetDeviceCOM(), &Mesh->m_SkinMesh))) ReleaseCOM(Mesh->m_SkinInfo); } // Create an array of matrices to store bone transformations if(Mesh->m_SkinInfo != NULL && Mesh->m_NumBones != 0) { // Create the bone matrix array and clear it out Mesh->m_Matrices = new D3DXMATRIX[Mesh->m_NumBones]; for(i=0;i<Mesh->m_NumBones;i++) D3DXMatrixIdentity(&Mesh->m_Matrices[i]); // Create the frame mapping matrix array and clear out Mesh->m_FrameMatrices = new D3DXMATRIX*[Mesh->m_NumBones]; for(i=0;i<Mesh->m_NumBones;i++) Mesh->m_FrameMatrices[i] = NULL; } // Load materials or create a default one if none if(!Mesh->m_NumMaterials) { // Create a default one Mesh->m_Materials = new D3DMATERIAL9[1]; Mesh->m_Textures = new LPDIRECT3DTEXTURE9[1]; ZeroMemory(Mesh->m_Materials, sizeof(D3DMATERIAL9)); Mesh->m_Materials[0].Diffuse.r = 1.0f; Mesh->m_Materials[0].Diffuse.g = 1.0f; Mesh->m_Materials[0].Diffuse.b = 1.0f; Mesh->m_Materials[0].Diffuse.a = 1.0f; Mesh->m_Materials[0].Ambient = Mesh->m_Materials[0].Diffuse; Mesh->m_Materials[0].Specular = Mesh->m_Materials[0].Diffuse; Mesh->m_Textures[0] = NULL; Mesh->m_NumMaterials = 1; } else { // Load the materials Materials = (D3DXMATERIAL*)MaterialBuffer->GetBufferPointer(); Mesh->m_Materials = new D3DMATERIAL9[Mesh->m_NumMaterials]; Mesh->m_Textures = new LPDIRECT3DTEXTURE9[Mesh->m_NumMaterials]; for(i=0;i<Mesh->m_NumMaterials;i++) { Mesh->m_Materials[i] = Materials[i].MatD3D; Mesh->m_Materials[i].Ambient = Mesh->m_Materials[i].Diffuse; // Build a texture path and load it sprintf(Path, "%s%s", TexturePath, Materials[i].pTextureFilename); if(FAILED(D3DXCreateTextureFromFile(m_Graphics->GetDeviceCOM(), Path, &Mesh->m_Textures[i]))) { Mesh->m_Textures[i] = NULL; } } } ReleaseCOM(MaterialBuffer); // link in mesh Mesh->m_Next = m_Meshes; m_Meshes = Mesh; m_NumMeshes++; } else { // Find mesh in list Mesh = m_Meshes->FindMesh(Name); } // Add mesh to frame if(Mesh != NULL) ParentFrame->AddMesh(Mesh); } // Skip animation sets and animations if(Type == TID_D3DRMAnimationSet || Type == TID_D3DRMAnimation || Type == TID_D3DRMAnimationKey) { delete [] Name; return; } // Release name buffer delete [] Name; SIZE_T count; if (FAILED(pDataObj->GetChildren(&count))) return; SIZE_T c = 0; // Scan for embedded templates while(c < count) { if (FAILED(pDataObj->GetChild(c, &pSubObj))) break; c++; // Process embedded references if (pSubObj->IsReference()) { if (SUCCEEDED(pSubObj->GetChild(0, &pSubData))) { ParseXFileData(pSubData, SubFrame, TexturePath); ReleaseCOM(pSubData); } } /*if(SUCCEEDED(pSubObj->QueryInterface(IID_IDirectXFileDataReference, (void**)&pDataRef))) { if(SUCCEEDED(pDataRef->Resolve(&pSubData))) { ParseXFileData(pSubData, SubFrame, TexturePath); ReleaseCOM(pSubData); } ReleaseCOM(pDataRef); }*/ // Process non-referenced embedded templates if(SUCCEEDED(pSubObj->QueryInterface(IID_ID3DXFileData, (void**)&pSubData))) { ParseXFileData(pSubData, SubFrame, TexturePath); ReleaseCOM(pSubData); } ReleaseCOM(pSubObj); } return; }
HRESULT Application::Init(HINSTANCE hInstance, bool windowed) { g_debug << "Application Started \n"; //Create Window Class WNDCLASS wc; memset(&wc, 0, sizeof(WNDCLASS)); wc.style = CS_HREDRAW | CS_VREDRAW; wc.lpfnWndProc = (WNDPROC)WndProc; wc.hInstance = hInstance; wc.lpszClassName = "D3DWND"; RECT rc = {0, 0, WINDOW_WIDTH, WINDOW_HEIGHT}; AdjustWindowRect(&rc, WS_OVERLAPPEDWINDOW, false); //Register Class and Create new Window RegisterClass(&wc); m_mainWindow = ::CreateWindow("D3DWND", "Character Animation with Direct3D: Example 8.3", WS_OVERLAPPEDWINDOW, 0, 0, rc.right - rc.left, rc.bottom - rc.top, 0, 0, hInstance, 0); SetCursor(NULL); ::ShowWindow(m_mainWindow, SW_SHOW); ::UpdateWindow(m_mainWindow); //Create IDirect3D9 Interface IDirect3D9* d3d9 = Direct3DCreate9(D3D_SDK_VERSION); if (d3d9 == NULL) { g_debug << "Direct3DCreate9() - FAILED \n"; return E_FAIL; } //Check that the Device supports what we need from it D3DCAPS9 caps; d3d9->GetDeviceCaps(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, &caps); //Check vertex & pixelshader versions if (caps.VertexShaderVersion < D3DVS_VERSION(2, 0) || caps.PixelShaderVersion < D3DPS_VERSION(2, 0)) { g_debug << "Warning - Your graphic card does not support vertex and pixelshaders version 2.0 \n"; } //Set D3DPRESENT_PARAMETERS m_present.BackBufferWidth = WINDOW_WIDTH; m_present.BackBufferHeight = WINDOW_HEIGHT; m_present.BackBufferFormat = D3DFMT_A8R8G8B8; m_present.BackBufferCount = 2; m_present.MultiSampleType = D3DMULTISAMPLE_NONE; m_present.MultiSampleQuality = 0; m_present.SwapEffect = D3DSWAPEFFECT_DISCARD; m_present.hDeviceWindow = m_mainWindow; m_present.Windowed = windowed; m_present.EnableAutoDepthStencil = true; m_present.AutoDepthStencilFormat = D3DFMT_D24S8; m_present.Flags = 0; m_present.FullScreen_RefreshRateInHz = D3DPRESENT_RATE_DEFAULT; m_present.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; //Hardware Vertex Processing int vp = 0; if ( caps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT ) vp = D3DCREATE_HARDWARE_VERTEXPROCESSING; else vp = D3DCREATE_SOFTWARE_VERTEXPROCESSING; //Create the IDirect3DDevice9 if (FAILED(d3d9->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, m_mainWindow, vp, &m_present, &g_pDevice))) { g_debug << "Failed to create IDirect3DDevice9 \n"; return E_FAIL; } //Release IDirect3D9 interface d3d9->Release(); //Load Application Specific resources here... D3DXCreateFont(g_pDevice, 20, 0, FW_BOLD, 1, false, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, "Arial", &g_pFont); //Create Sprite D3DXCreateSprite(g_pDevice, &g_pSprite); //Load Lighting shader ID3DXBuffer *pErrorMsgs = NULL; HRESULT hRes = D3DXCreateEffectFromFile(g_pDevice, "resources/fx/skinning.fx", NULL, NULL, D3DXSHADER_DEBUG, NULL, &g_pEffect, &pErrorMsgs); if (FAILED(hRes) && (pErrorMsgs != NULL)) { //Failed to create Effect g_debug << (char*)pErrorMsgs->GetBufferPointer() << "\n"; } m_deviceLost = false; m_morphTest.Init(); return S_OK; }
int r3dPixelShader :: Load( const char* FName, int Type, const r3dTL::TArray <D3DXMACRO> & defines ) { R3D_ENSURE_MAIN_THREAD(); sprintf(FileName, "%s\\%s", __r3dBaseShaderPath, FName); char defines_string[256]; memset(defines_string, 0, 256); for(unsigned int i=0; i<defines.Count(); ++i) { sprintf(&defines_string[strlen(defines_string)], "%s=%s,", defines[i].Name, defines[i].Definition); } if ( !LoadBinaryCache( FName, FileName, defines_string ) ) { ID3DXBuffer* pCode; HRESULT hr; r3dTL::TArray <D3DXMACRO> definesCpy( defines ); definesCpy.PushBack(D3DXMACRO()); definesCpy[definesCpy.Count() - 1].Name = "VERTEX_SHADER"; definesCpy[definesCpy.Count() - 1].Definition = "0"; definesCpy.PushBack(D3DXMACRO()); definesCpy[definesCpy.Count() - 1].Name = "PIXEL_SHADER"; definesCpy[definesCpy.Count() - 1].Definition = "1"; definesCpy.PushBack(D3DXMACRO()); definesCpy[definesCpy.Count() - 1].Name = 0; definesCpy[definesCpy.Count() - 1].Definition = 0; r3dTL::TArray < r3dString > Includes; if( !r3dCompileShader( FileName, &definesCpy[0], "main", r3dRenderer->PixelShaderProfileName, &pCode, &Includes )) return 0; Unload(); // Create the pixel shader hr = r3dRenderer->pd3ddev->CreatePixelShader( (DWORD*)pCode->GetBufferPointer(), &m_pShader); r3dRenderer->CheckOutOfMemory( hr ) ; if( FAILED(hr) ) { r3dOutToLog("Failed to create Pixel shader '%s' : ", FileName); if(hr == D3DERR_INVALIDCALL) r3dOutToLog ("Invalid Call\n"); if(hr == E_OUTOFMEMORY) r3dOutToLog ("Out of memory\n"); if(hr == D3DERR_OUTOFVIDEOMEMORY) r3dOutToLog ("Out of Video Memory\n"); else r3dOutToLog("error: %d\n", hr); m_pShader = NULL; pCode->Release(); return 0; } #ifdef _DEBUG _r3d_mShaderMap.insert(std::pair<DWORD, std::string>((DWORD)m_pShader, FileName)); //r3dOutToLog("Shader[%x] created : %d, %s\n", m_dwShader, _iNumShaders, FileName); #endif SaveBinaryCache( FName, pCode, defines_string, Includes ); pCode->Release(); } // save macros for reloading possibility ( TODO : make optional & disabled in final build ) Macros.Resize( defines.Count() ); for( uint32_t i = 0, e = defines.Count(); i < e ; i ++ ) { ShaderMacro& macro = Macros[ i ]; const D3DXMACRO& dxmacro = defines[ i ]; macro.Name = dxmacro.Name; macro.Definition = dxmacro.Definition; } return 1; }
bool InitVertexBuffer() { HRESULT hr; ID3DXBuffer *adjBuff = NULL; ID3DXBuffer *mtrlBuff = NULL; DWORD numMtrls = 0; // 메쉬 정보 로드 hr = D3DXLoadMeshFromXA( "../../media/bigship1.x", D3DXMESH_MANAGED, g_pDevice, &adjBuff, &mtrlBuff, 0, &numMtrls, &g_pMesh ); if (FAILED(hr)) return false; ///////////////////////////////////////////////////////////////////////////// // 매터리얼 설정 if( mtrlBuff && numMtrls > 0 ) { D3DXMATERIAL *mtrls = (D3DXMATERIAL*)mtrlBuff->GetBufferPointer(); for( int i=0; i < (int)numMtrls; ++i ) { mtrls[ i].MatD3D.Ambient = mtrls[ i].MatD3D.Diffuse; g_Mtrls.push_back( mtrls[ i].MatD3D ); if( mtrls[ i].pTextureFilename ) { IDirect3DTexture9 *tex = NULL; string filePath = "../../media/"; filePath += mtrls[ i].pTextureFilename; D3DXCreateTextureFromFileA( g_pDevice, filePath.c_str(), &tex ); g_Texture.push_back( tex ); } else { g_Texture.push_back( 0 ); } } } mtrlBuff->Release(); // 메쉬 최적화 hr = g_pMesh->OptimizeInplace( D3DXMESHOPT_COMPACT | D3DXMESHOPT_ATTRSORT | D3DXMESHOPT_VERTEXCACHE, (DWORD*)adjBuff->GetBufferPointer(), (DWORD*)adjBuff->GetBufferPointer(), 0, 0 ); if (FAILED(hr)) return false; // 프로그레시브 메쉬 생성. hr = D3DXGeneratePMesh(g_pMesh, (DWORD*)adjBuff->GetBufferPointer(), 0, 0, 1, D3DXMESHSIMP_FACE, &g_pPMesh ); g_pMesh->Release(); g_pMesh = NULL; adjBuff->Release(); if (FAILED(hr)) return false; //DWORD maxFaces = g_pPMesh->GetMaxFaces(); //g_pPMesh->SetNumFaces( maxFaces ); D3DXCOLOR color(1,1,1,1); ZeroMemory(&g_Light, sizeof(g_Light)); g_Light.Type = D3DLIGHT_DIRECTIONAL; g_Light.Ambient = color * 0.4f; g_Light.Diffuse = color; g_Light.Specular = color * 0.6f; g_Light.Direction = *(D3DXVECTOR3*)&Vector3(0,-1,0); Matrix44 V; Vector3 camPos(0,0,-20); Vector3 lookAtPos(0,0,0); Vector3 dir = lookAtPos - camPos; dir.Normalize(); V.SetView(camPos, dir, Vector3(0,1,0)); g_pDevice->SetTransform(D3DTS_VIEW, (D3DXMATRIX*)&V); Matrix44 proj; proj.SetProjection(D3DX_PI * 0.5f, (float)WINSIZE_X / (float) WINSIZE_Y, 1.f, 1000.0f) ; g_pDevice->SetTransform(D3DTS_PROJECTION, (D3DXMATRIX*)&proj) ; g_pDevice->SetLight(0, &g_Light); // 광원 설정. g_pDevice->LightEnable( 0, // 활성화/ 비활성화 하려는 광원 리스트 내의 요소 true); // true = 활성화 , false = 비활성화 g_pDevice->SetRenderState(D3DRS_NORMALIZENORMALS, true); g_pDevice->SetRenderState(D3DRS_SPECULARENABLE, true); return true; }
void XManager::loadXFile(IDirect3DDevice9* dev, const std::string& filename, ID3DXMesh** meshOut, std::vector<Material>* mtrls, std::vector<IDirect3DTexture9*>* texs) { // Step 1: Load the .x file from file into a system memory mesh. ID3DXMesh* meshSys = 0; ID3DXBuffer* adjBuffer = 0; ID3DXBuffer* mtrlBuffer = 0; DWORD numMtrls = 0; HR(D3DXLoadMeshFromX(filename.c_str(), D3DXMESH_SYSTEMMEM, dev, &adjBuffer, &mtrlBuffer, 0, &numMtrls, &meshSys)); // Step 2: Find out if the mesh already has normal info? D3DVERTEXELEMENT9 elems[MAX_FVF_DECL_SIZE]; HR(meshSys->GetDeclaration(elems)); bool hasNormals = false; D3DVERTEXELEMENT9 term = D3DDECL_END(); for(int i = 0; i < MAX_FVF_DECL_SIZE; ++i) { // Did we reach D3DDECL_END() {0xFF,0,D3DDECLTYPE_UNUSED, 0,0,0}? if(elems[i].Stream == 0xff ) break; if( elems[i].Type == D3DDECLTYPE_FLOAT3 && elems[i].Usage == D3DDECLUSAGE_NORMAL && elems[i].UsageIndex == 0 ) { hasNormals = true; break; } } // Step 3: Change vertex format to CustomVertex3NormalUV D3DVERTEXELEMENT9 elements[64]; UINT numElements = 0; CustomVertex3NormalUV::decl->GetDeclaration(elements, &numElements); ID3DXMesh* temp = 0; HR(meshSys->CloneMesh(D3DXMESH_SYSTEMMEM, elements, dev, &temp)); SAFERELEASECOM(meshSys); meshSys = temp; // Step 4: If the mesh did not have normals, generate them. if( hasNormals == false) HR(D3DXComputeNormals(meshSys, 0)); // Step 5: Optimize the mesh. HR(meshSys->Optimize(D3DXMESH_MANAGED | D3DXMESHOPT_COMPACT | D3DXMESHOPT_ATTRSORT | D3DXMESHOPT_VERTEXCACHE, (DWORD*)adjBuffer->GetBufferPointer(), 0, 0, 0, meshOut)); SAFERELEASECOM(meshSys); // Done w/ system mesh. SAFERELEASECOM(adjBuffer); // Done with buffer. // Step 6: Extract the materials and load the textures. if( mtrlBuffer != 0 && numMtrls != 0 ) { D3DXMATERIAL* d3dxmtrls = (D3DXMATERIAL*)mtrlBuffer->GetBufferPointer(); for(DWORD i = 0; i < numMtrls; ++i) { // Save the ith material. Note that the MatD3D property does not have an ambient // value set when its loaded, so just set it to the diffuse value. Material m; m.ambient = d3dxmtrls[i].MatD3D.Diffuse; m.diffuse = d3dxmtrls[i].MatD3D.Diffuse; m.spec = d3dxmtrls[i].MatD3D.Specular; m.specPower = d3dxmtrls[i].MatD3D.Power; mtrls->push_back( m ); // Check if the ith material has an associative texture if( d3dxmtrls[i].pTextureFilename != 0 ) { IDirect3DTexture9* tex = 0; std::string s(d3dxmtrls[i].pTextureFilename); const char folder[] = "./texture/"; unsigned int pos = s.find_last_of('\/'); std::string newFileName(folder); // std::string::npos gets returned if no / was found if(pos != std::string::npos) { //std::string sub = s.substr(pos,s.size()); if(strcmp(s.substr(pos+1,s.size()).c_str(),"Watcher.tga") == 0) { newFileName.append("Watcher_Black.tga"); } else { newFileName.append(s.substr(pos+1,s.size())); } } else { newFileName.append(s); } // Save the loaded texture HR(D3DXCreateTextureFromFile(dev, newFileName.c_str(), &tex)); texs->push_back( tex ); } else {
void CShowPoints9::SetMesh(LPD3DXMESH pNewMesh, LPD3DXSKININFO pNewSkin) { HRESULT hr = S_OK; NumPoints = 0; UnskinnedVB.resize(0); SAFE_RELEASE(SkinnedVB); SAFE_RELEASE(Skin); if(pNewMesh == NULL) return; IDirect3DDevice9* device = DXUTGetD3D9Device(); {//EFFECT V( device->CreateVertexDeclaration( Elements, &Declaration ) ); ID3DXBuffer* pErrors = NULL; V( SASCreateEffectFromResource( device, NULL, MAKEINTRESOURCE(IDR_SHOWLINES9FX), MAKEINTRESOURCE(RT_RCDATA), NULL, NULL, 0, NULL, &Effect, &pErrors)); if(pErrors) DXVGetApp().OutputA( (const char*)pErrors->GetBufferPointer() ); SAFE_RELEASE(pErrors); }//EFFECT D3DVERTEXELEMENT9 declIn[ MAX_FVF_DECL_SIZE ]; V( pNewMesh->GetDeclaration(declIn) ); int iPos= -1; int iNorm= -1; for( int i = 0 ; declIn[i].Stream != 255 && i < MAX_FVF_DECL_SIZE; i++) { if(declIn[i].Usage == D3DDECLUSAGE_POSITION && declIn[i].UsageIndex == 0) iPos = i; if(declIn[i].Usage == D3DDECLUSAGE_NORMAL && declIn[i].UsageIndex == 0) iNorm = i; } if(iPos == -1 || iNorm == -1) return; if( (( declIn[iPos].Type & (D3DDECLTYPE_FLOAT3|D3DDECLTYPE_FLOAT4)) == 0 ) || (( declIn[iNorm].Type & (D3DDECLTYPE_FLOAT3|D3DDECLTYPE_FLOAT4)) == 0 ) ) return; NumPoints = pNewMesh->GetNumVertices(); int MeshStride = pNewMesh->GetNumBytesPerVertex(); if(pNewSkin) { V( pNewSkin->Clone( &Skin ) ); V( Skin->SetDeclaration(Elements) ); } //GET VERTEX DATA BYTE* pSrcVB= NULL; V( pNewMesh->LockVertexBuffer( D3DLOCK_READONLY, (LPVOID*)&pSrcVB ) ); UnskinnedVB.resize(pNewMesh->GetNumVertices()); for( DWORD iVert = 0; iVert < pNewMesh->GetNumVertices(); iVert++) { Vertex& v0 = UnskinnedVB[iVert]; v0.Position = *(D3DXVECTOR3*) (pSrcVB+(MeshStride*iVert)+declIn[iPos].Offset); } V( pNewMesh->UnlockVertexBuffer() ); V( device->CreateVertexBuffer( NumPoints*Stride , D3DUSAGE_WRITEONLY, 0, D3DPOOL_MANAGED, &SkinnedVB, NULL) ); //Fill in with initial values so unskinned meshes do not have to do this every render. pSrcVB=(BYTE*)(void*)&UnskinnedVB.front(); BYTE* pDstVB=NULL; V( SkinnedVB->Lock(0, 0, (void**)&pDstVB, 0 ) ); { memcpy( pDstVB, pSrcVB, Stride*pNewMesh->GetNumVertices() ); } V( SkinnedVB->Unlock() ); }
bool Efx::Initialize() { HRESULT hresult = 0; ID3DXBuffer* errorBuffer = 0; hresult = D3DXCreateEffectFromFile( d3ddev, "Lighting Effect.txt", NULL, NULL, D3DXSHADER_DEBUG, NULL, &LightingEffect, &errorBuffer); if( errorBuffer ) { MessageBox(0, (char*)errorBuffer->GetBufferPointer(), 0, 0); errorBuffer->Release(); } if(FAILED(hresult)) { MessageBox(0, "D3DXCompileEffectFromFile() - FAILED", 0, 0); return false; } ID3DXBuffer* errorBufferS = 0; hresult = D3DXCreateEffectFromFile( d3ddev, "Lighting Effect Simple.txt", NULL, NULL, D3DXSHADER_DEBUG, NULL, &LightingEffectSimple, &errorBufferS); if( errorBufferS ) { MessageBox(0, (char*)errorBufferS->GetBufferPointer(), 0, 0); errorBufferS->Release(); } if(FAILED(hresult)) { MessageBox(0, "D3DXCompileEffectFromFile() - FAILED", 0, 0); return false; } ID3DXBuffer* errorBufferBloom = 0; hresult = D3DXCreateEffectFromFile( d3ddev, "Bloom Effect.txt", NULL, NULL, D3DXSHADER_DEBUG, NULL, &BloomEffect, &errorBufferBloom); if( errorBufferBloom ) { MessageBox(0, (char*)errorBufferBloom->GetBufferPointer(), 0, 0); errorBufferBloom->Release(); } if(FAILED(hresult)) { MessageBox(0, "D3DXCompileEffectFromFile() - FAILED", 0, 0); return false; } ID3DXBuffer* errorBufferCell = 0; hresult = D3DXCreateEffectFromFile( d3ddev, "Cell Shading Effect.txt", NULL, NULL, D3DXSHADER_DEBUG, NULL, &CellEffect, &errorBufferCell); if( errorBufferCell ) { MessageBox(0, (char*)errorBufferCell->GetBufferPointer(), 0, 0); errorBufferCell->Release(); } if(FAILED(hresult)) { MessageBox(0, "D3DXCompileEffectFromFile() - FAILED", 0, 0); return false; } ID3DXBuffer* errorBufferOutline = 0; hresult = D3DXCreateEffectFromFile( d3ddev, "Outline Effect.txt", NULL, NULL, D3DXSHADER_DEBUG, NULL, &OutlineEffect, &errorBufferOutline); if( errorBufferOutline ) { MessageBox(0, (char*)errorBufferOutline->GetBufferPointer(), 0, 0); errorBufferOutline->Release(); } if(FAILED(hresult)) { MessageBox(0, "D3DXCompileEffectFromFile() - FAILED", 0, 0); return false; } ViewProjMHandle = LightingEffect->GetParameterByName(0, "ViewProj"); ViewMatrixMHandle = LightingEffect->GetParameterByName(0, "ViewMatrix"); ViewProjMatrixMHandle = LightingEffect->GetParameterByName(0, "ViewProjMatrix"); AmbientMtrlMHandle = LightingEffect->GetParameterByName(0, "AmbientMtrl"); DiffuseMtrlMHandle = LightingEffect->GetParameterByName(0, "DiffuseMtrl"); LightDirMHandle = LightingEffect->GetParameterByName(0, "LightDirection"); FogOnMHandle = LightingEffect->GetParameterByName(0, "FogOn"); AmbientIntensitySHandle = LightingEffectSimple->GetParameterByName(0, "AmbientIntensity"); DiffuseIntensitySHandle = LightingEffectSimple->GetParameterByName(0, "DiffuseIntensity"); ViewProjSHandle = LightingEffectSimple->GetParameterByName(0, "ViewProj"); ViewMatrixSHandle = LightingEffectSimple->GetParameterByName(0, "ViewMatrix"); ViewProjMatrixSHandle = LightingEffectSimple->GetParameterByName(0, "ViewProjMatrix"); AmbientMtrlSHandle = LightingEffectSimple->GetParameterByName(0, "AmbientMtrl"); DiffuseMtrlSHandle = LightingEffectSimple->GetParameterByName(0, "DiffuseMtrl"); LightDirSHandle = LightingEffectSimple->GetParameterByName(0, "LightDirection"); FogOnSHandle = LightingEffectSimple->GetParameterByName(0, "FogOn"); TexAMHandle = LightingEffect->GetParameterByName(0, "TexA"); TexBMHandle = LightingEffect->GetParameterByName(0, "TexB"); TexCMHandle = LightingEffect->GetParameterByName(0, "TexC"); OpacTexBMHandle = LightingEffect->GetParameterByName(0, "OpacTexB"); OpacTexCMHandle = LightingEffect->GetParameterByName(0, "OpacTexC"); CameraPositionMHandle = LightingEffect->GetParameterByName(0, "CameraPosition"); CameraPositionSHandle = LightingEffectSimple->GetParameterByName(0, "CameraPosition"); TexSHandle = LightingEffectSimple->GetParameterByName(0, "Tex"); BloomGameTextureHandle = BloomEffect->GetParameterByName(0, "GameColor"); BloomTextureHandle = BloomEffect->GetParameterByName(0, "BloomColor"); ViewProjCHandle = CellEffect->GetParameterByName(0, "ViewProj"); ViewMatrixCHandle = CellEffect->GetParameterByName(0, "ViewMatrix"); ViewProjMatrixCHandle = CellEffect->GetParameterByName(0, "ViewProjMatrix"); LightDirCHandle = CellEffect->GetParameterByName(0, "LightDirection"); TexCHandle = CellEffect->GetParameterByName(0, "Tex"); FogOnCHandle = CellEffect->GetParameterByName(0, "FogOn"); CameraPositionCHandle = CellEffect->GetParameterByName(0, "CameraPosition"); ProjOHandle = OutlineEffect->GetParameterByName(0, "Proj"); ViewMatrixOHandle = OutlineEffect->GetParameterByName(0, "ViewMatrix"); return true; }
void SkinnedMesh::buildSkinnedMesh(ID3DXMesh* mesh) { //==================================================================== // First add a normal component and 2D texture coordinates component. D3DVERTEXELEMENT9 elements[64]; UINT numElements = 0; VertexPNT::Decl->GetDeclaration(elements, &numElements); ID3DXMesh* tempMesh = 0; HR(mesh->CloneMesh(D3DXMESH_SYSTEMMEM, elements, gd3dDevice, &tempMesh)); if( !hasNormals(tempMesh) ) HR(D3DXComputeNormals(tempMesh, 0)); //==================================================================== // Optimize the mesh; in particular, the vertex cache. DWORD* adj = new DWORD[tempMesh->GetNumFaces()*3]; ID3DXBuffer* remap = 0; HR(tempMesh->GenerateAdjacency(EPSILON, adj)); ID3DXMesh* optimizedTempMesh = 0; HR(tempMesh->Optimize(D3DXMESH_SYSTEMMEM | D3DXMESHOPT_VERTEXCACHE | D3DXMESHOPT_ATTRSORT, adj, 0, 0, &remap, &optimizedTempMesh)); ReleaseCOM(tempMesh); // Done w/ this mesh. delete[] adj; // Done with buffer. // In the .X file (specifically the array DWORD vertexIndices[nWeights] // data member of the SkinWeights template) each bone has an array of // indices which identify the vertices of the mesh that the bone influences. // Because we have just rearranged the vertices (from optimizing), the vertex // indices of a bone are obviously incorrect (i.e., they index to vertices the bone // does not influence since we moved vertices around). In order to update a bone's // vertex indices to the vertices the bone _does_ influence, we simply need to specify // where we remapped the vertices to, so that the vertex indices can be updated to // match. This is done with the ID3DXSkinInfo::Remap method. HR(mSkinInfo->Remap(optimizedTempMesh->GetNumVertices(), (DWORD*)remap->GetBufferPointer())); ReleaseCOM(remap); // Done with remap info. //==================================================================== // The vertex format of the source mesh does not include vertex weights // nor bone index data, which are both needed for vertex blending. // Therefore, we must convert the source mesh to an "indexed-blended-mesh," // which does have the necessary data. DWORD numBoneComboEntries = 0; ID3DXBuffer* boneComboTable = 0; HR(mSkinInfo->ConvertToIndexedBlendedMesh(optimizedTempMesh, D3DXMESH_MANAGED | D3DXMESH_WRITEONLY, MAX_NUM_BONES_SUPPORTED, 0, 0, 0, 0, &mMaxVertInfluences, &numBoneComboEntries, &boneComboTable, &mSkinnedMesh)); ReleaseCOM(optimizedTempMesh); // Done with tempMesh. ReleaseCOM(boneComboTable); // Don't need bone table. #if defined(DEBUG) | defined(_DEBUG) // Output to the debug output the vertex declaration of the mesh at this point. // This is for insight only to see what exactly ConvertToIndexedBlendedMesh // does to the vertex declaration. D3DVERTEXELEMENT9 elems[MAX_FVF_DECL_SIZE]; HR(mSkinnedMesh->GetDeclaration(elems)); OutputDebugString("\nVertex Format After ConvertToIndexedBlendedMesh\n"); int i = 0; while( elems[i].Stream != 0xff ) // While not D3DDECL_END() { if( elems[i].Type == D3DDECLTYPE_FLOAT1) OutputDebugString("Type = D3DDECLTYPE_FLOAT1; "); if( elems[i].Type == D3DDECLTYPE_FLOAT2) OutputDebugString("Type = D3DDECLTYPE_FLOAT2; "); if( elems[i].Type == D3DDECLTYPE_FLOAT3) OutputDebugString("Type = D3DDECLTYPE_FLOAT3; "); if( elems[i].Type == D3DDECLTYPE_UBYTE4) OutputDebugString("Type = D3DDECLTYPE_UBYTE4; "); if( elems[i].Usage == D3DDECLUSAGE_POSITION) OutputDebugString("Usage = D3DDECLUSAGE_POSITION\n"); if( elems[i].Usage == D3DDECLUSAGE_BLENDWEIGHT) OutputDebugString("Usage = D3DDECLUSAGE_BLENDWEIGHT\n"); if( elems[i].Usage == D3DDECLUSAGE_BLENDINDICES) OutputDebugString("Usage = D3DDECLUSAGE_BLENDINDICES\n"); if( elems[i].Usage == D3DDECLUSAGE_NORMAL) OutputDebugString("Usage = D3DDECLUSAGE_NORMAL\n"); if( elems[i].Usage == D3DDECLUSAGE_TEXCOORD) OutputDebugString("Usage = D3DDECLUSAGE_TEXCOORD\n"); ++i; } #endif }
BOOL jcd3d::jcd3d_setup() { jcd3d_setProjectionPerspectiveTransform(jcd3d_lpd3dd, 800, 600); jcd3d_setViewTransform(jcd3d_lpd3dd, 2.0f, 2.0f, -2.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f); jcd3d_initRenderState(jcd3d_lpd3dd, D3DCULL_CCW, FALSE, TRUE, D3DSHADE_GOURAUD, D3DFILL_SOLID, FALSE); D3DXMATRIX worldMatrix; D3DXMatrixIdentity(&worldMatrix); jcd3d_lpd3dd->SetTransform(D3DTS_WORLD, &worldMatrix); xVerifyFailedIf(jcd3d_lpd3dd->CreateIndexBuffer(3 * sizeof(WORD), D3DUSAGE_WRITEONLY, D3DFMT_INDEX16, D3DPOOL_MANAGED, &lpib, NULL)) xVerifyFailedEndIf WORD* lpibData = NULL; xVerifyFailedIf(lpib->Lock(0, 3 * sizeof(WORD), (VOID**)&lpibData, NULL)) return FALSE; xVerifyFailedEndIf lpibData[0] = 0; lpibData[1] = 1; lpibData[2] = 2; xVerifyFailedIf(lpib->Unlock()) xVerifyFailedEndIf xVerifyFailedIf(jcd3d_lpd3dd->CreateVertexBuffer(3 * sizeof(JCD3D_Vertex_xyz_diffuse), D3DUSAGE_WRITEONLY, JCD3D_Vertex_xyz_diffuse::FVF, D3DPOOL_MANAGED, &lpvb1, NULL)) return FALSE; xVerifyFailedEndIf JCD3D_Vertex_xyz_diffuse* lpvb1Data = NULL; xVerifyFailedIf(lpvb1->Lock(0, 3 * sizeof(JCD3D_Vertex_xyz_diffuse), (VOID**)&lpvb1Data, 0)) return FALSE; xVerifyFailedEndIf lpvb1Data[0].x = -1.0f; lpvb1Data[0].y = -1.0f, lpvb1Data[0].z = 0.0f; lpvb1Data[0].color = 0xFF0000; lpvb1Data[1].x = -1.0f; lpvb1Data[1].y = 1.0f, lpvb1Data[1].z = 0.0f; lpvb1Data[1].color = 0x00FF00; lpvb1Data[2].x = 1.0f; lpvb1Data[2].y = -1.0f, lpvb1Data[2].z = 0.0f; lpvb1Data[2].color = 0x0000FF; xVerifyFailedIf(lpvb1->Unlock()) return FALSE; xVerifyFailedEndIf xVerifyFailedIf(jcd3d_lpd3dd->CreateVertexBuffer(3 * sizeof(JCD3D_Vertex_xyz_diffuse), D3DUSAGE_WRITEONLY, JCD3D_Vertex_xyz_diffuse::FVF, D3DPOOL_MANAGED, &lpvb2, NULL)) return FALSE; xVerifyFailedEndIf JCD3D_Vertex_xyz_diffuse* lpvb2Data = NULL; xVerifyFailedIf(lpvb2->Lock(0, 3 * sizeof(JCD3D_Vertex_xyz_diffuse), (VOID**)&lpvb2Data, 0)) return FALSE; xVerifyFailedEndIf lpvb2Data[0].x = -1.0f; lpvb2Data[0].y = -1.0f, lpvb2Data[0].z = -1.0f; lpvb2Data[0].color = 0xFF0000; lpvb2Data[1].x = -1.0f; lpvb2Data[1].y = 1.0f, lpvb2Data[1].z = -1.0f; lpvb2Data[1].color = 0x00FF00; lpvb2Data[2].x = 1.0f; lpvb2Data[2].y = -1.0f, lpvb2Data[2].z = -1.0f; lpvb2Data[2].color = 0x0000FF; xVerifyFailedIf(lpvb2->Unlock()) return FALSE; xVerifyFailedEndIf ID3DXBuffer* lpShaderBuffer = NULL; ID3DXBuffer* lpErrorBuffer = NULL; xVerifyFailedIf(D3DXCompileShaderFromFileA("testVS.vs", NULL, NULL, "Main", "vs_1_1", D3DXSHADER_ENABLE_BACKWARDS_COMPATIBILITY, &lpShaderBuffer, &lpErrorBuffer, &lpConstantTable)) return FALSE; xVerifyFailedEndIf if(lpErrorBuffer != NULL) { CHAR* errMsg = (CHAR*)lpErrorBuffer->GetBufferPointer(); MessageBoxA(jcd3d_hwnd, errMsg, "Error", MB_OK); jccommon_releaseComM(lpErrorBuffer); return FALSE; } jccommon_releaseComM(lpErrorBuffer); xVerifyFailedIf(jcd3d_lpd3dd->CreateVertexShader((DWORD*)lpShaderBuffer->GetBufferPointer(), &lpVertexShader)) jccommon_releaseComM(lpShaderBuffer); return FALSE; xVerifyFailedEndIf jccommon_releaseComM(lpShaderBuffer); hMatrixWVP = lpConstantTable->GetConstantByName(NULL, "gWVP"); hScalar = lpConstantTable->GetConstantByName(NULL, "gScalar"); D3DXMATRIX viewMatrix; xVerifyFailedIf(jcd3d_lpd3dd->GetTransform(D3DTS_VIEW, &viewMatrix)) return FALSE; xVerifyFailedEndIf D3DXMATRIX projectionMatrix; xVerifyFailedIf(jcd3d_lpd3dd->GetTransform(D3DTS_PROJECTION, &projectionMatrix)) return FALSE; xVerifyFailedEndIf D3DXMATRIX vwpMatrix = worldMatrix * viewMatrix * projectionMatrix; xVerifyFailedIf(lpConstantTable->SetMatrix(jcd3d_lpd3dd, hMatrixWVP, &vwpMatrix)) return FALSE; xVerifyFailedEndIf xVerifyFailedIf(lpConstantTable->SetDefaults(jcd3d_lpd3dd)) return FALSE; xVerifyFailedEndIf D3DVERTEXELEMENT9 vertexDeclaration[] = { {0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0}, {0, 12, D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR, 0}, {1, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 1}, D3DDECL_END() }; xVerifyFailedIf(jcd3d_lpd3dd->CreateVertexDeclaration(vertexDeclaration, &lpVertexDeclaration)) return FALSE; xVerifyFailedEndIf return TRUE; }
void SSAO::reloadShader() { // Setup the defines for compiling the effect vector<D3DXMACRO> defines; // Setup pixel size macro stringstream sp; sp << "float2(1.0 / " << width << ", 1.0 / " << height << ")"; string pixelSizeText = sp.str(); D3DXMACRO pixelSizeMacro = { "PIXEL_SIZE", pixelSizeText.c_str() }; defines.push_back(pixelSizeMacro); // Setup SRGB macro D3DXMACRO srgbMacro = { "USE_SRGB", useSRGB ? "true" : "false" }; defines.push_back(srgbMacro); // Setup depth reading method D3DXMACRO readHWDepthMacro = { "USE_HWDEPTH", "true" }; if(readHWDepth) defines.push_back(readHWDepthMacro); // Setup scale macro stringstream ss; ss << Settings::get().getSsaoScale() << ".0"; string scaleText = ss.str(); D3DXMACRO scaleMacro = { "SCALE", scaleText.c_str() }; defines.push_back(scaleMacro); // Setup strength macro D3DXMACRO strengthMacros[] = { { "SSAO_STRENGTH_LOW", "1" }, { "SSAO_STRENGTH_MEDIUM", "1" }, { "SSAO_STRENGTH_HIGH", "1" } }; defines.push_back(strengthMacros[strength]); // Setup blur macro if(blur == BLUR_SHARP) { D3DXMACRO sharpBlur = { "BLUR_SHARP", "1" }; defines.push_back(sharpBlur); } D3DXMACRO null = { NULL, NULL }; defines.push_back(null); DWORD flags = D3DXFX_NOT_CLONEABLE | D3DXSHADER_OPTIMIZATION_LEVEL3; // Load effect from file string shaderFn; switch(type) { case VSSAO: shaderFn = "VSSAO.fx"; break; case HBAO: shaderFn = "HBAO.fx"; break; case SCAO: shaderFn = "SCAO.fx"; break; case VSSAO2: shaderFn = "VSSAO2.fx"; break; } shaderFn = getAssetFileName(shaderFn); SDLOG(0, "%s load, scale %s, strength %s\n", shaderFn.c_str(), scaleText.c_str(), strengthMacros[strength].Name); ID3DXBuffer* errors; ID3DXEffect* newEffect; HRESULT hr = D3DXCreateEffectFromFile(device, shaderFn.c_str(), &defines.front(), NULL, flags, NULL, &newEffect, &errors); if(hr != D3D_OK) { SDLOG(-1, "ERRORS:\n %s\n", errors->GetBufferPointer()); Console::get().add(format("Error compiling %s:", shaderFn.c_str())); Console::get().add(static_cast<const char*>(errors->GetBufferPointer())); } else { SAFERELEASE(effect); effect = newEffect; } // get handles depthTexHandle = effect->GetParameterByName(NULL, "depthTex2D"); frameTexHandle = effect->GetParameterByName(NULL, "frameTex2D"); prevPassTexHandle = effect->GetParameterByName(NULL, "prevPassTex2D"); }
HRESULT XTexShader:: InitShader(const char* vertexShader,const char* pixelShader,D3DDevice *pDevice) { //------------------------------------------------------------------------------------- // Vertex Shader and Pixel Shader //------------------------------------------------------------------------------------- TextFile *vert,*pix; vert = ResourceManager::GetInstance()->Load<TextFile>(vertexShader); pix = ResourceManager::GetInstance()->Load<TextFile>(pixelShader); string sVert,sPix; sVert = vert->GetFileContents(); sPix = pix->GetFileContents(); ID3DXBuffer* pVertexShaderCode; ID3DXBuffer* pVertexErrorMessage; //Creating Vertex Shader HRESULT hr = D3DXCompileShader(sVert.c_str(),strlen(sVert.c_str()),NULL,NULL,"main","vs_2_0",0,&pVertexShaderCode,&pVertexErrorMessage,NULL); if(FAILED(hr)) { if(pVertexErrorMessage) OutputDebugString((char*)pVertexErrorMessage->GetBufferPointer()); return E_FAIL; } pDevice->CreateVertexShader((DWORD*)pVertexShaderCode->GetBufferPointer(),&m_pVertexShader); ID3DXBuffer* pPixelShaderCode; ID3DXBuffer* pPixelErrorMessage; //Creating Pixel Shader hr = D3DXCompileShader(sPix.c_str(),strlen(sPix.c_str()),NULL,NULL,"main","ps_2_0",0,&pPixelShaderCode,&pPixelErrorMessage,NULL); if(FAILED(hr)) { if(pPixelErrorMessage) OutputDebugString((char*)pPixelErrorMessage->GetBufferPointer()); return E_FAIL; } pDevice->CreatePixelShader((DWORD*)pPixelShaderCode->GetBufferPointer(),&m_pPixelShader); //Creating Vertex Declaration D3DVERTEXELEMENT9 VertexElements[3]= { { 0, 0,D3DDECLTYPE_FLOAT3,D3DDECLMETHOD_DEFAULT,D3DDECLUSAGE_POSITION,0}, { 0, 12, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 }, D3DDECL_END() }; if (FAILED(pDevice->CreateVertexDeclaration(VertexElements, &m_pVertDec))) return S_FALSE; if(FAILED(CreateVertBuffer())) return S_FALSE; return S_OK; }
//-------------------------------------------------------------------------------------- //LoadShaderFromResource // //loads shader given a resource id //-------------------------------------------------------------------------------------- HRESULT CEffect::LoadShaderFromResource(uint32 a_ResourceID, IDirect3DDevice9 *a_pDevice) { HRESULT hr; ID3DXBuffer *errorBuffer; HRSRC resourceInfo; HGLOBAL resourceData; char8 *shaderText; m_pDevice = a_pDevice; //delete old effect if multiple calls to load shader are made SAFE_RELEASE(m_pEffect); // Define DEBUG_VS and/or DEBUG_PS to debug vertex and/or pixel shaders with the // shader debugger. Debugging vertex shaders requires either REF or software vertex // processing, and debugging pixel shaders requires REF. The // D3DXSHADER_FORCE_*_SOFTWARE_NOOPT flag improves the debug experience in the // shader debugger. It enables source level debugging, prevents instruction // reordering, prevents dead code elimination, and forces the compiler to compile // against the next higher available software target, which ensures that the // unoptimized shaders do not exceed the shader model limitations. Setting these // flags will cause slower rendering since the shaders will be unoptimized and // forced into software. See the DirectX documentation for more information about // using the shader debugger. DWORD dwShaderFlags = 0; #ifdef DEBUG_VS dwShaderFlags |= D3DXSHADER_FORCE_VS_SOFTWARE_NOOPT; #endif #ifdef DEBUG_PS dwShaderFlags |= D3DXSHADER_FORCE_PS_SOFTWARE_NOOPT; #endif //load shadertext from resource resourceInfo = FindResource(NULL, MAKEINTRESOURCE(a_ResourceID), L"EFFECTFILE"); if(resourceInfo == NULL) { _snwprintf_s(m_ErrorMsg, MAX_ERROR_MSG, MAX_ERROR_MSG, L"Resource %d of type ''EFFECTFILE'' not found.", a_ResourceID ); } resourceData = LoadResource(NULL, resourceInfo ); shaderText = (char8 *)LockResource( resourceData); //Create effect from text loaded from resource // load and compile .fx file // If this fails, there should be debug output as to // why the .fx file failed to compile hr = D3DXCreateEffect( m_pDevice, //LPDIRECT3DDEVICE9 pDevice, shaderText, //LPCVOID pSrcData, (uint32)SizeofResource(NULL, resourceInfo), //UINT SrcDataLen, NULL, //const D3DXMACRO *pDefines, NULL, //LPD3DXINCLUDE pInclude, 0, //DWORD Flags, NULL, //LPD3DXEFFECTPOOL pPool, &m_pEffect, //LPD3DXEFFECT *ppEffect, &errorBuffer //LPD3DXBUFFER *ppCompilationErrors ); UnlockResource( resourceData ); FreeResource( resourceData ); //return failure and record error message if failure if(FAILED(hr)) { //error is in 8-bit character format, so for swprintf to use the string, %S (capital S) is used. if(errorBuffer != NULL) { _snwprintf_s(m_ErrorMsg, MAX_ERROR_MSG, MAX_ERROR_MSG, L"Shader Compile Error: %S.", errorBuffer->GetBufferPointer() ); } else { _snwprintf_s(m_ErrorMsg, MAX_ERROR_MSG, MAX_ERROR_MSG, L"Shader Compile Error: no output from D3DXCreateEffectFromResource." ); } SAFE_RELEASE(errorBuffer); return hr; } _snwprintf_s(m_ErrorMsg, MAX_ERROR_MSG, MAX_ERROR_MSG, L"FX file in Resource %d Compiled Successfully.", a_ResourceID); return S_OK; }
bool Setup() { HRESULT hr; ID3DXBuffer* mtrlBuffer = 0; DWORD numMtrl = 0; hr = D3DXLoadMeshFromX( L"mountain.x", D3DXMESH_MANAGED, Device, 0, &mtrlBuffer, 0, &numMtrl, &pMesh); if (FAILED(hr)) { ::MessageBoxA(0, "D3DXLoadMeshFromX() - Failed!", 0, 0); return false; } if (mtrlBuffer != 0 && numMtrl != 0) { D3DXMATERIAL* mtrls = (D3DXMATERIAL*)mtrlBuffer->GetBufferPointer(); for (DWORD i = 0; i < numMtrl; ++i) { mtrls[i].MatD3D.Ambient = mtrls[i].MatD3D.Diffuse; Mtrls.push_back(mtrls[i].MatD3D); if (mtrls[i].pTextureFilename != 0) { IDirect3DTexture9* tex = 0; D3DXCreateTextureFromFileA( Device, mtrls[i].pTextureFilename, &tex); Textures.push_back(tex); } else { Textures.push_back(0); } } } mtrlBuffer->Release(); ID3DXBuffer* pError; hr = D3DXCreateEffectFromFile( Device, L"light_tex.txt", 0, 0, D3DXSHADER_DEBUG, 0, &pLightTexEffect, &pError); if (FAILED(hr)) { ::MessageBoxA(0, (char*)pError->GetBufferPointer(), 0, 0); return false; } hWorldMatrix = pLightTexEffect->GetParameterByName(0, "WorldMatrix"); hViewMatrix = pLightTexEffect->GetParameterByName(0, "ViewMatrix"); hProjMatrix = pLightTexEffect->GetParameterByName(0, "ProjMatrix"); hTex = pLightTexEffect->GetParameterByName(0, "Tex"); hLightTexTech = pLightTexEffect->GetTechniqueByName("LightAndTexture"); D3DXMATRIX W, P; D3DXMatrixIdentity(&W); pLightTexEffect->SetMatrix(hWorldMatrix, &W); D3DXMatrixPerspectiveFovLH( &P, D3DX_PI*0.25f, (float)Width / Height, 1.0f, 1000.0f); pLightTexEffect->SetMatrix(hProjMatrix, &P); IDirect3DTexture9* tex = 0; D3DXCreateTextureFromFile(Device, L"Terrain_3x_diffcol.jpg", &tex); pLightTexEffect->SetTexture(hTex, tex); tex->Release(); return true; }
bool d3dbase::LoadXFileMesh(ID3DXMesh** pMesh, std::string strFilename,IDirect3DDevice9* Device, std::vector<D3DMATERIAL9>& Mtrls, std::vector<IDirect3DTexture9*>& Textures) { HRESULT hr = 0; ID3DXBuffer* adjBuffer = 0;//adj info of the mesh ID3DXBuffer* mtrlBuffer = 0;//material info of the mesh DWORD numMtrls = 0;//此模型中包括的材质、纹理的个数 hr = D3DXLoadMeshFromX( strFilename.c_str(), D3DXMESH_MANAGED, Device, &adjBuffer, &mtrlBuffer, //此模型的材质、纹理由它返回 0, &numMtrls, pMesh); //调试语句 if(D3DERR_INVALIDCALL== hr) { int j = 0; } if(E_OUTOFMEMORY == hr) { int h = 1; } if(FAILED(hr)) { ::MessageBox(0, "D3DXLoadMeshFromX() - FAILED", 0, 0); return false; } // //由mtrlBuffer得到材质和纹理 // if( mtrlBuffer != NULL && numMtrls != 0 ) { D3DXMATERIAL* mtrls = (D3DXMATERIAL*)mtrlBuffer->GetBufferPointer(); //void* -->D3DXMATERIAL* for(int i = 0; i < numMtrls; i++) { //MatD3D加载时没有设置ambient分量,在这里设置为与Diffuse分量相同 mtrls[i].MatD3D.Ambient = mtrls[i].MatD3D.Diffuse; // 存储材质集 Mtrls.push_back( mtrls[i].MatD3D ); //检查第i个材质是否有相应的纹理图 if( mtrls[i].pTextureFilename != 0 ) { // 有的话从相应文件加载 if(GetFileDir(const_cast<char*>(strFilename.c_str()))) strcat(g_FileDir,mtrls[i].pTextureFilename); else strcpy(g_FileDir,mtrls[i].pTextureFilename); IDirect3DTexture9* tex = 0; D3DXCreateTextureFromFile( Device, g_FileDir, &tex); // 并存储 Textures.push_back( tex ); } else { // 否则就为 NULL Textures.push_back( 0 ); } } } d3dbase::Release<ID3DXBuffer*>(mtrlBuffer); // 已经从mtrlBuffer解析完纹理与材质,释放mtrlBuffer //根据邻接矩阵优化模型 hr = (*pMesh)->OptimizeInplace( D3DXMESHOPT_ATTRSORT | D3DXMESHOPT_COMPACT | D3DXMESHOPT_VERTEXCACHE, (DWORD*)adjBuffer->GetBufferPointer(), 0, 0, 0); d3dbase::Release<ID3DXBuffer*>(adjBuffer); // 释放adjBuffer if(FAILED(hr)) { ::MessageBox(0, "OptimizeInplace() - FAILED", 0, 0); return false; } return true; }
Scaler::Scaler(IDirect3DDevice9 *device, int inputwidth, int inputheight, int width, int height, bool useSRGB) : Effect(device), inputwidth(inputwidth), inputheight(inputheight), width(width), height(height), levels(0), levelInputSizes(NULL) { SDLOG(0, "Scaler construct\n"); // Determine initial scaling type from settings if(boost::iequals(Settings::get().getScalingType(), string("bicubic"))) { sType = BICUBIC; } else if(boost::iequals(Settings::get().getScalingType(), string("lanczos"))) { sType = LANCZOS; } else if(boost::iequals(Settings::get().getScalingType(), string("nearest"))) { sType = NEAREST; } else { sType = BILINEAR; } // Setup the defines for compiling the effect vector<D3DXMACRO> defines; D3DXMACRO srgbMacro = { "USE_SRGB", useSRGB ? "true" : "false" }; defines.push_back(srgbMacro); D3DXMACRO null = { NULL, NULL }; defines.push_back(null); DWORD flags = D3DXFX_NOT_CLONEABLE | D3DXSHADER_OPTIMIZATION_LEVEL3; // Load effect from file SDLOG(0, "Scaler load\n"); ID3DXBuffer* errors; HRESULT hr = D3DXCreateEffectFromFile(device, getAssetFileName("scaling.fx").c_str(), &defines.front(), NULL, flags, NULL, &effect, &errors); if(hr != D3D_OK) SDLOG(0, "ERRORS:\n %s\n", errors->GetBufferPointer()); // get handles frameTexHandle = effect->GetParameterByName(NULL, "frameTex2D"); inputSizeHandle = effect->GetParameterByName(NULL, "inputSize"); stringstream ss; // generate multi-level buffers levels = max( max(0, static_cast<int>(ceil(Log2(static_cast<double>(inputwidth)/width)-1))), max(0, static_cast<int>(ceil(Log2(static_cast<double>(inputheight)/height)-1))) ); SDLOG(2, "Scaler: Generating %u multi-level buffers\n", levels); ss << "Downsampling: " << levels+1 << " level" << (levels?"s ":" "); levelInputSizes = new FLOAT[levels*2+2]; levelInputSizes[levels*2+0] = static_cast<FLOAT>(width*2); levelInputSizes[levels*2+1] = static_cast<FLOAT>(height*2); levelBuffers.resize(levels); for(int i=levels-1; i>=0; --i) { unsigned w = static_cast<unsigned>(levelInputSizes[(i+1)*2+0]); unsigned h = static_cast<unsigned>(levelInputSizes[(i+1)*2+1]); levelInputSizes[i*2+0] = static_cast<FLOAT>(w*2); levelInputSizes[i*2+1] = static_cast<FLOAT>(h*2); levelBuffers[i] = RSManager::getRTMan().createTexture(w, h, RenderTarget::FMT_ARGB_8); SDLOG(2, "Multi-level buffer %u: %p - size: %ux%u\n", i, levelBuffers[i], w, h); } levelInputSizes[0] = static_cast<FLOAT>(inputwidth); levelInputSizes[1] = static_cast<FLOAT>(inputheight); for(unsigned i=0; i<levels+1; i++) { SDLOG(2, "Scaling step %u: input size: %5.0f x %5.0f\n", i, levelInputSizes[i*2+0], levelInputSizes[i*2+1]); ss << format("%5.0f x %5.0f -> ", levelInputSizes[i*2+0], levelInputSizes[i*2+1]); } ss << format("%5d x %5d", Settings::get().getPresentWidth(), Settings::get().getPresentHeight()); status = ss.str(); showStatus(); }
void LoadXFile( const std::string& filename, ID3DXMesh** meshOut, std::vector<Mtrl>& mtrls, std::vector<IDirect3DTexture9*>& texs) { // Step 1: Load the .x file from file into a system memory mesh. ID3DXMesh* meshSys = 0; ID3DXBuffer* adjBuffer = 0; ID3DXBuffer* mtrlBuffer = 0; DWORD numMtrls = 0; HR(D3DXLoadMeshFromX(filename.c_str(), D3DXMESH_SYSTEMMEM, gd3dDevice, &adjBuffer, &mtrlBuffer, 0, &numMtrls, &meshSys)); // Step 2: Find out if the mesh already has normal info? D3DVERTEXELEMENT9 elems[MAX_FVF_DECL_SIZE]; HR(meshSys->GetDeclaration(elems)); bool hasNormals = false; D3DVERTEXELEMENT9 term = D3DDECL_END(); for(int i = 0; i < MAX_FVF_DECL_SIZE; ++i) { // Did we reach D3DDECL_END() {0xFF,0,D3DDECLTYPE_UNUSED, 0,0,0}? if(elems[i].Stream == 0xff ) break; if( elems[i].Type == D3DDECLTYPE_FLOAT3 && elems[i].Usage == D3DDECLUSAGE_NORMAL && elems[i].UsageIndex == 0 ) { hasNormals = true; break; } } // Step 3: Change vertex format to VertexPNT. D3DVERTEXELEMENT9 elements[64]; UINT numElements = 0; VertexPNT::Decl->GetDeclaration(elements, &numElements); ID3DXMesh* temp = 0; HR(meshSys->CloneMesh(D3DXMESH_SYSTEMMEM, elements, gd3dDevice, &temp)); ReleaseCOM(meshSys); meshSys = temp; // Step 4: If the mesh did not have normals, generate them. if( hasNormals == false) HR(D3DXComputeNormals(meshSys, 0)); // Step 5: Optimize the mesh. HR(meshSys->Optimize(D3DXMESH_MANAGED | D3DXMESHOPT_COMPACT | D3DXMESHOPT_ATTRSORT | D3DXMESHOPT_VERTEXCACHE, (DWORD*)adjBuffer->GetBufferPointer(), 0, 0, 0, meshOut)); ReleaseCOM(meshSys); // Done w/ system mesh. ReleaseCOM(adjBuffer); // Done with buffer. // Step 6: Extract the materials and load the textures. if( mtrlBuffer != 0 && numMtrls != 0 ) { D3DXMATERIAL* d3dxmtrls = (D3DXMATERIAL*)mtrlBuffer->GetBufferPointer(); for(DWORD i = 0; i < numMtrls; ++i) { // Save the ith material. Note that the MatD3D property does not have an ambient // value set when its loaded, so just set it to the diffuse value. Mtrl m; m.ambient = d3dxmtrls[i].MatD3D.Diffuse; m.diffuse = d3dxmtrls[i].MatD3D.Diffuse; m.spec = d3dxmtrls[i].MatD3D.Specular; m.specPower = d3dxmtrls[i].MatD3D.Power; mtrls.push_back( m ); // Check if the ith material has an associative texture if( d3dxmtrls[i].pTextureFilename != 0 ) { // Yes, load the texture for the ith subset IDirect3DTexture9* tex = 0; char* texFN = d3dxmtrls[i].pTextureFilename; HR(D3DXCreateTextureFromFile(gd3dDevice, texFN, &tex)); // Save the loaded texture texs.push_back( tex ); } else { // No texture for the ith subset texs.push_back( 0 ); } } } ReleaseCOM(mtrlBuffer); // done w/ buffer }
HRESULT CRender::shader_compile ( LPCSTR name, LPCSTR pSrcData, UINT SrcDataLen, void* _pDefines, void* _pInclude, LPCSTR pFunctionName, LPCSTR pTarget, DWORD Flags, void* _ppShader, void* _ppErrorMsgs, void* _ppConstantTable) { D3DXMACRO defines [128]; int def_it = 0; CONST D3DXMACRO* pDefines = (CONST D3DXMACRO*) _pDefines; if (pDefines) { // transfer existing defines for (;;def_it++) { if (0==pDefines[def_it].Name) break; defines[def_it] = pDefines[def_it]; } } // options if (o.forceskinw) { defines[def_it].Name = "SKIN_COLOR"; defines[def_it].Definition = "1"; def_it ++; } if (m_skinning<0) { defines[def_it].Name = "SKIN_NONE"; defines[def_it].Definition = "1"; def_it ++; } if (0==m_skinning) { defines[def_it].Name = "SKIN_0"; defines[def_it].Definition = "1"; def_it ++; } if (1==m_skinning) { defines[def_it].Name = "SKIN_1"; defines[def_it].Definition = "1"; def_it ++; } if (2==m_skinning) { defines[def_it].Name = "SKIN_2"; defines[def_it].Definition = "1"; def_it ++; } // finish defines[def_it].Name = 0; defines[def_it].Definition = 0; def_it ++; R_ASSERT (def_it<128); LPD3DXINCLUDE pInclude = (LPD3DXINCLUDE) _pInclude; LPD3DXBUFFER* ppShader = (LPD3DXBUFFER*) _ppShader; LPD3DXBUFFER* ppErrorMsgs = (LPD3DXBUFFER*) _ppErrorMsgs; LPD3DXCONSTANTTABLE* ppConstantTable = (LPD3DXCONSTANTTABLE*)_ppConstantTable; #ifdef D3DXSHADER_USE_LEGACY_D3DX9_31_DLL // December 2006 and later HRESULT _result = D3DXCompileShader(pSrcData,SrcDataLen,defines,pInclude,pFunctionName,pTarget,Flags|D3DXSHADER_USE_LEGACY_D3DX9_31_DLL,ppShader,ppErrorMsgs,ppConstantTable); #else HRESULT _result = D3DXCompileShader(pSrcData,SrcDataLen,defines,pInclude,pFunctionName,pTarget,Flags,ppShader,ppErrorMsgs,ppConstantTable); #endif if (SUCCEEDED(_result) && o.disasm) { ID3DXBuffer* code = *((LPD3DXBUFFER*)_ppShader); ID3DXBuffer* disasm = 0; D3DXDisassembleShader (LPDWORD(code->GetBufferPointer()), FALSE, 0, &disasm ); string_path dname; strconcat (sizeof(dname),dname,"disasm\\",name,('v'==pTarget[0])?".vs":".ps" ); IWriter* W = FS.w_open("$logs$",dname); W->w (disasm->GetBufferPointer(),disasm->GetBufferSize()); FS.w_close (W); _RELEASE (disasm); } return _result; }
// // Framework functions // bool Setup() { HRESULT hr = 0; // // Load the XFile data. // ID3DXBuffer* adjBuffer = 0; ID3DXBuffer* mtrlBuffer = 0; DWORD numMtrls = 0; hr = D3DXLoadMeshFromX( "../media/object/bigship1.x", D3DXMESH_MANAGED, Device, &adjBuffer, &mtrlBuffer, 0, &numMtrls, &Mesh); if(FAILED(hr)) { ::MessageBox(0, "D3DXLoadMeshFromX() - FAILED", 0, 0); return false; } // // Extract the materials, load textures. // if( mtrlBuffer != 0 && numMtrls != 0 ) { D3DXMATERIAL* mtrls = (D3DXMATERIAL*)mtrlBuffer->GetBufferPointer(); for(int i = 0; i < numMtrls; i++) { // the MatD3D property doesn't have an ambient value set // when its loaded, so set it now: mtrls[i].MatD3D.Ambient = mtrls[i].MatD3D.Diffuse; // save the ith material Mtrls.push_back( mtrls[i].MatD3D ); // check if the ith material has an associative texture if( mtrls[i].pTextureFilename != 0 ) { // yes, load the texture for the ith subset IDirect3DTexture9* tex = 0; D3DXCreateTextureFromFile( Device, mtrls[i].pTextureFilename, &tex); // save the loaded texture Textures.push_back( tex ); } else { // no texture for the ith subset Textures.push_back( 0 ); } } } byhj::Release<ID3DXBuffer*>(mtrlBuffer); // done w/ buffer // // Optimize the mesh. // hr = Mesh->OptimizeInplace( D3DXMESHOPT_ATTRSORT | D3DXMESHOPT_COMPACT | D3DXMESHOPT_VERTEXCACHE, (DWORD*)adjBuffer->GetBufferPointer(), 0, 0, 0); byhj::Release<ID3DXBuffer*>(adjBuffer); // done w/ buffer if(FAILED(hr)) { ::MessageBox(0, "OptimizeInplace() - FAILED", 0, 0); return false; } // // Compute Bounding Sphere and Bounding Box. // byhj::BoundingSphere boundingSphere; byhj::BoundingBox boundingBox; ComputeBoundingSphere(Mesh, &boundingSphere); ComputeBoundingBox(Mesh, &boundingBox); D3DXCreateSphere( Device, boundingSphere._radius, 20, 20, &SphereMesh, 0); D3DXCreateBox( Device, boundingBox._max.x - boundingBox._min.x, boundingBox._max.y - boundingBox._min.y, boundingBox._max.z - boundingBox._min.z, &BoxMesh, 0); // // Set texture filters. // Device->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR); Device->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR); Device->SetSamplerState(0, D3DSAMP_MIPFILTER, D3DTEXF_POINT); // // Set Lights. // D3DXVECTOR3 dir(1.0f, -1.0f, 1.0f); D3DXCOLOR col(1.0f, 1.0f, 1.0f, 1.0f); D3DLIGHT9 light = byhj::InitDirectionalLight(&dir, &col); Device->SetLight(0, &light); Device->LightEnable(0, true); Device->SetRenderState(D3DRS_NORMALIZENORMALS, true); Device->SetRenderState(D3DRS_SPECULARENABLE, true); // // Set camera. // D3DXVECTOR3 pos(4.0f, 12.0f, -20.0f); D3DXVECTOR3 target(0.0f, 0.0f, 0.0f); D3DXVECTOR3 up(0.0f, 1.0f, 0.0f); D3DXMATRIX V; D3DXMatrixLookAtLH( &V, &pos, &target, &up); Device->SetTransform(D3DTS_VIEW, &V); // // Set projection matrix. // D3DXMATRIX proj; D3DXMatrixPerspectiveFovLH( &proj, D3DX_PI * 0.5f, // 90 - degree (float)Width / (float)Height, 1.0f, 1000.0f); Device->SetTransform(D3DTS_PROJECTION, &proj); return true; }
//------------------------------------------------------------------------- bool CMeshLoadX::Setup(IDirect3DDevice9* pDevice,int nWidth,int nHeight) { if (0 == pDevice) { return false; } m_Device = pDevice; m_nHeight = nHeight; m_nWidth = nWidth; // 读取X文件并解析 { HRESULT hr = 0; ID3DXBuffer* adjBuffer = 0; ID3DXBuffer* mtrlBuffer = 0; DWORD numMtrls = 0; hr = D3DXLoadMeshFromX( s_szMeshFilePath, D3DXMESH_MANAGED, m_Device, &adjBuffer, &mtrlBuffer, 0, &numMtrls, &m_SourceMesh); if (FAILED(hr)) { ::MessageBox(0,"CMeshLoadX::Setup hr is failed",0,0); return false; } if (mtrlBuffer != 0 && numMtrls != 0) { D3DXMATERIAL* mtrls = (D3DXMATERIAL*)mtrlBuffer->GetBufferPointer(); for (int nIndex = 0; nIndex < numMtrls; ++nIndex) { mtrls[nIndex].MatD3D.Ambient = mtrls[nIndex].MatD3D.Diffuse; m_vecMtrls.push_back(mtrls[nIndex].MatD3D); if (mtrls[nIndex].pTextureFilename != 0) { IDirect3DTexture9* pTex = 0; D3DXCreateTextureFromFile(m_Device,mtrls[nIndex].pTextureFilename,&pTex); m_vecTextures.push_back(pTex); } else { m_vecTextures.push_back(0); } } } d3d::Release<ID3DXBuffer*>(mtrlBuffer); hr = m_SourceMesh->OptimizeInplace( D3DXMESHOPT_ATTRSORT | D3DXMESHOPT_COMPACT | D3DXMESHOPT_VERTEXCACHE, (DWORD*)adjBuffer->GetBufferPointer(), (DWORD*)adjBuffer->GetBufferPointer(), // new adjacency info 0, 0); if(FAILED(hr)) { ::MessageBox(0, "OptimizeInplace() - FAILED", 0, 0); return false; } hr = D3DXGeneratePMesh( m_SourceMesh, (DWORD*)adjBuffer->GetBufferPointer(), 0, 0, 1, D3DXMESHSIMP_FACE, &m_ProcessMesh); if(FAILED(hr)) { ::MessageBox(0, "D3DXGeneratePMesh() - FAILED", 0, 0); return false; } m_ProcessMesh->SetNumFaces(m_ProcessMesh->GetMaxFaces()); d3d::Release<ID3DXBuffer*>(adjBuffer); // done w/ buffer } // 新建字体 { D3DXFONT_DESCA lf; ::ZeroMemory(&lf,sizeof(D3DXFONT_DESCA)); lf.Height = 25; lf.Width = 14; lf.Weight = 500; lf.Italic = false; lf.CharSet = DEFAULT_CHARSET; #pragma warning ( disable: 4996 ) strcpy(lf.FaceName,"Times New Roman"); #pragma warning ( default : 4996 ) D3DXCreateFontIndirect(m_Device,&lf,&m_XFont); } // 写Mesh数据文件 { m_OutFile.open("MeshDumpX.txt"); __dumpVertices(m_OutFile, m_SourceMesh); __dumpIndices(m_OutFile, m_SourceMesh); __dumpAttributeTable(m_OutFile, m_SourceMesh); __dumpAttributeBuffer(m_OutFile, m_SourceMesh); __dumpAdjacencyBuffer(m_OutFile, m_SourceMesh); m_OutFile.close(); } d3d::BoundingSphere boundingSphere; d3d::BoundingBox boundingBox; __ComputeBoundingSphere(m_SourceMesh, &boundingSphere); __ComputeBoundingBox(m_SourceMesh, &boundingBox); D3DXCreateSphere( m_Device, boundingSphere._radius, 20, 20, &m_SphereMesh, 0); D3DXCreateBox( m_Device, boundingBox._max.x - boundingBox._min.x, boundingBox._max.y - boundingBox._min.y, boundingBox._max.z - boundingBox._min.z, &m_BoxMesh, 0); // // Set texture filters. // m_Device->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR); m_Device->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR); m_Device->SetSamplerState(0, D3DSAMP_MIPFILTER, D3DTEXF_POINT); // // Set Lights. // D3DXVECTOR3 dir(1.0f, -1.0f, 1.0f); D3DXCOLOR col(1.0f, 1.0f, 1.0f, 1.0f); D3DLIGHT9 light = d3d::InitDirectionalLight(&dir, &col); m_Device->SetLight(0, &light); m_Device->LightEnable(0, true); m_Device->SetRenderState(D3DRS_NORMALIZENORMALS, true); m_Device->SetRenderState(D3DRS_SPECULARENABLE, true); // // Set camera. // D3DXVECTOR3 pos(4.0f, 4.0f, -20.0f); D3DXVECTOR3 target(0.0f, 0.0f, 0.0f); D3DXVECTOR3 up(0.0f, 1.0f, 0.0f); D3DXMATRIX V; D3DXMatrixLookAtLH( &V, &pos, &target, &up); m_Device->SetTransform(D3DTS_VIEW, &V); // // Set projection matrix. // D3DXMATRIX proj; D3DXMatrixPerspectiveFovLH( &proj, D3DX_PI * 0.5f, // 90 - degree (float)m_nWidth / (float)m_nHeight, 1.0f, 1000.0f); m_Device->SetTransform(D3DTS_PROJECTION, &proj); return true; }
HRESULT CRacorX::RestoreDeviceObjects() { IDirect3DDevice8* device; HRESULT hr = m_spD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, m_hWnd, m_iVP, &m_dpps, &device); if (FAILED(hr)) { OutputDebugString(L"Create Device Failed! Error:\n"); switch (hr) { case D3DERR_DEVICELOST: OutputDebugString(L"D3DERR_DEVICELOST\n"); break; case D3DERR_INVALIDCALL: OutputDebugString(L"D3DERR_INVALIDCALL\n"); break; case D3DERR_NOTAVAILABLE: OutputDebugString(L"D3DERR_NOTAVAILABLE\n"); break; case D3DERR_OUTOFVIDEOMEMORY: OutputDebugString(L"D3DERR_OUTOFVIDEOMEMORY\n"); break;; default: OutputDebugString(L"Unknown\n"); break; } return S_FALSE; } m_spDevice.reset(device, [](IDirect3DDevice8* device){ device->Release(); }); DWORD dwDecl0[] = { D3DVSD_STREAM(0), D3DVSD_REG(0,D3DVSDT_FLOAT3), //D3DVSD_REG(5,D3DVSDT_D3DCOLOR), /*D3DVSD_CONST(0, 4), *(DWORD*)&m_mtWorld[0], *(DWORD*)&m_mtWorld[1], *(DWORD*)&m_mtWorld[2], *(DWORD*)&m_mtWorld[3], *(DWORD*)&m_mtWorld[4], *(DWORD*)&m_mtWorld[5], *(DWORD*)&m_mtWorld[6], *(DWORD*)&m_mtWorld[7], *(DWORD*)&m_mtWorld[8], *(DWORD*)&m_mtWorld[9], *(DWORD*)&m_mtWorld[10], *(DWORD*)&m_mtWorld[11], *(DWORD*)&m_mtWorld[12], *(DWORD*)&m_mtWorld[13], *(DWORD*)&m_mtWorld[14], *(DWORD*)&m_mtWorld[15], D3DVSD_CONST(0, 1), *(DWORD*)&m_fMaterial[0], *(DWORD*)&m_fMaterial[1], *(DWORD*)&m_fMaterial[2], *(DWORD*)&m_fMaterial[3],*/ D3DVSD_END() }; IDirect3DVertexBuffer8* vb; m_spDevice->CreateVertexBuffer( 4 * sizeof (Vertex), D3DUSAGE_WRITEONLY, Vertex::FVF, D3DPOOL_MANAGED, &vb); m_spVB.reset(vb, [](IDirect3DVertexBuffer8* vb){ vb->Release(); }); Vertex* vertices = 0; m_spVB->Lock(0, 0, reinterpret_cast<BYTE**>(&vertices), 0); vertices[0] = { -100.0f, -100.0f, 0.0f, }; vertices[1] = { 100.0f, -100.0f, 0.0f, }; vertices[2] = { 100.0f, 100.0f, 0.0f, }; vertices[3] = { -100.0f, 100.0f, 0.0f, }; /* vertices[0] = { -1.0f, -1.0f, 0.2f, }; vertices[1] = { 1.0f, -1.0f, 0.2f, }; vertices[2] = { 1.0f, 1.0f, 0.2f, }; vertices[3] = { -1.0f, 1.0f, 0.2f, }; */ m_spVB->Unlock(); IDirect3DIndexBuffer8* ib; m_spDevice->CreateIndexBuffer( 6 * sizeof(WORD), D3DUSAGE_WRITEONLY, D3DFMT_INDEX16, D3DPOOL_MANAGED, &ib); m_spIB.reset(ib, [](IDirect3DIndexBuffer8* ib){ ib->Release(); }); WORD *indices = 0; m_spIB->Lock(0, 0, reinterpret_cast<BYTE**>(&indices), 0); indices[0] = 0; indices[1] = 1; indices[2] = 2; indices[3] = 0; indices[4] = 2; indices[5] = 3; m_spIB->Unlock(); const char vsh[] = "vs.1.1 \n" \ "dp4 oPos.x, v0, c0 \n"\ "dp4 oPos.y, v0, c1 \n"\ "dp4 oPos.z, v0, c2 \n"\ "dp4 oPos.w, v0, c3 \n"\ "mov oD0, c4\n"; /* const char vsh[] = "vs.1.1 \n" \ "mov oPos, v0 \n" \ "mov oD0, c4 \n"; */ ID3DXBuffer* pVBuffer; ID3DXBuffer* pErrors; HRESULT rc = D3DXAssembleShader(reinterpret_cast<LPCVOID>(vsh), sizeof(vsh) - 1, 0, NULL, &pVBuffer, &pErrors); if (FAILED(rc)) { OutputDebugString(L"Failed to assemble the vertex shader, error:\n"); OutputDebugStringA(reinterpret_cast<CHAR*>(pErrors->GetBufferPointer())); OutputDebugString(L"\n"); } rc = m_spDevice->CreateVertexShader(dwDecl0, (DWORD*)pVBuffer->GetBufferPointer(), &m_dwVertexShader, 0); if (FAILED(rc)) { OutputDebugString(L"Failed to create vertex shader, error:\n"); WCHAR szBuffer[512] = { 0 }; D3DXGetErrorString(rc, szBuffer, sizeof(szBuffer)); OutputDebugString(szBuffer); OutputDebugString(L"\n"); } m_spDevice->SetViewport(&m_Viewport); //m_spDevice->SetTransform(D3DTS_VIEW, &m_mtView); //m_spDevice->SetTransform(D3DTS_PROJECTION, &m_mtProj); m_spDevice->SetRenderState(D3DRS_ZENABLE, true); m_spDevice->SetRenderState(D3DRS_LIGHTING, false); //m_spDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID); m_spDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE); return S_OK; }
void CompileShaders() { ID3DXBuffer* pShaderCode = NULL; ID3DXBuffer* pErrorMsg = NULL; HRESULT hr = -1; #ifdef _XBOX // Compile vertex shader. hr = D3DXCompileShader( vscode, (UINT)strlen( vscode ), NULL, NULL, "main", "vs_2_0", 0, &pShaderCode, &pErrorMsg, NULL ); #endif if( FAILED(hr) ) { OutputDebugStringA((CHAR*)pErrorMsg->GetBufferPointer()); DebugBreak(); } // Create pixel shader. pD3Ddevice->CreateVertexShader( (DWORD*)pShaderCode->GetBufferPointer(), &pFramebufferVertexShader ); pShaderCode->Release(); #ifdef _XBOX // Compile pixel shader. hr = D3DXCompileShader( pscode, (UINT)strlen( pscode ), NULL, NULL, "main", "ps_2_0", 0, &pShaderCode, &pErrorMsg, NULL ); #endif if( FAILED(hr) ) { OutputDebugStringA((CHAR*)pErrorMsg->GetBufferPointer()); DebugBreak(); } // Create pixel shader. pD3Ddevice->CreatePixelShader( (DWORD*)pShaderCode->GetBufferPointer(), &pFramebufferPixelShader ); pShaderCode->Release(); pD3Ddevice->CreateVertexDeclaration( VertexElements, &pFramebufferVertexDecl ); pD3Ddevice->SetVertexDeclaration( pFramebufferVertexDecl ); pD3Ddevice->CreateVertexDeclaration( SoftTransVertexElements, &pSoftVertexDecl ); }