D3D11 法线贴图(凹凸贴图)
本章將學(xué)習(xí)如何讓一張平坦的紋理表面具有深度感,該技術(shù)叫法線貼圖。這里是基于前面加載obj模型的章節(jié)構(gòu)建的,但不會(huì)使用那個(gè)模型,而會(huì)使用一個(gè)更為簡(jiǎn)單的地面草地紋理的模型。
法線貼圖技術(shù)要做的事情就是讓普通紋理在使能光照時(shí)看起來有凹凸深度感。它是通過給每個(gè)像素而不是給每個(gè)頂點(diǎn)定義法線來實(shí)現(xiàn)的,然后插值到整個(gè)表面。為了實(shí)現(xiàn)該技術(shù),要使用紋理(Texture)或切線(Tangent)空間(與世界或本地視圖空間類比)。
紋理/切線空間
也許會(huì)疑惑為什么不直接使用法線貼圖來做凹凸呢?這是因?yàn)榉ň€貼圖的法線先要轉(zhuǎn)換到插值法線(頂點(diǎn)法線)空間,而實(shí)際上不能夠直接將法線貼圖的法線轉(zhuǎn)換到物體世界空間。這是因?yàn)槲矬w上的每個(gè)頂點(diǎn)可能會(huì)有不同的位置,法線和紋理坐標(biāo),意味著在物體上每個(gè)三角形的面都朝向不同的方向以及有著不同的紋理坐標(biāo),因此這么做后就必須要將法線貼圖的法線轉(zhuǎn)換到每個(gè)三角形而不是物體世界空間了。
若試著將一張凹凸感的貼圖貼到到立方體上。法線貼圖法線方向默認(rèn)是指向相機(jī)的,同時(shí)立方體的前面是朝向相機(jī)的,再將法線貼圖和立方體放入世界空間,假設(shè)讓它們旋轉(zhuǎn)90度。若直接將法線貼圖轉(zhuǎn)換到世界空間,會(huì)看到立方體的右面(就是之前的前面)有得到凹凸感,這是因?yàn)榉ň€貼圖同時(shí)也旋轉(zhuǎn)了90度,此時(shí)所有的法線貼圖的法線都指向右邊(而之前是指向相機(jī)的)。然而,立方體其他的面也會(huì)試著要使用轉(zhuǎn)換過的法線貼圖,但是現(xiàn)在都只指向右邊。這導(dǎo)致立方體上所有的法線方向都指向右邊,而不是指向每個(gè)面。這就是為什么需要為物體上的每個(gè)面使用獨(dú)立的空間來實(shí)現(xiàn)法線貼圖。
表示紋理空間的軸被稱為法線(Normal),副切線(Bitangent),和切線(Tangent)(T,B,N)。法線表示面所指向的方向,副切線和切線類似面的U,V紋理坐標(biāo)。
法線Normal
從每個(gè)頂點(diǎn)處獲取法線,然后使用像素著色器把它插值到整個(gè)平面,之后將在此做法線貼圖。
切線Tangent
切線是紋理坐標(biāo)的V軸。這里聲明兩個(gè)向量表示面的兩個(gè)邊(類似之前在加載obj章節(jié)計(jì)算法線時(shí)所做的),再聲明兩個(gè)2d向量為那個(gè)面表示紋理坐標(biāo)的兩條邊,隨后就能得到基于這些邊的切線。為每個(gè)向量計(jì)算切線并且存儲(chǔ)在向量結(jié)構(gòu)體中。由于法線插值緣故,在像素著色器中法線和切線不會(huì)總是正交的,在法線方向上可通過截?cái)嗲芯€方向來確保它們都在像素著色器中。必須確保法線和切線夾角為45°。
副切線Bitangent
副切線有時(shí)也叫做副法線,實(shí)際上副法線是錯(cuò)誤的說法。副法線是需要與NURBS以及圓表面或其他要素一起發(fā)揮作用的,而副切線是紋理坐標(biāo)的U軸。在像素著色器中(凹凸貼圖存在)為每個(gè)像素創(chuàng)建副切線,可通過叉乘切線和法線得到副切線(確認(rèn)切線和法線是正交之后)。
法線貼圖
法線貼圖是一張上面每個(gè)像素的顏色通道(eg.RGB)表示其法線的圖片,代碼中rgb會(huì)被插值表示為xyz,三維方向矢量。通常會(huì)看到法線貼圖是藍(lán)色的,是因?yàn)樗{(lán)色部分由z軸表示,z軸向上,同時(shí)法線面遠(yuǎn)離表面導(dǎo)致的。
可以用很多方法制作法線貼圖,其中一種方式使用photoshop,可從nvidia官網(wǎng)下載??上戎谱饕粡埰谕陌纪官N圖紋理,再把它轉(zhuǎn)為凹凸貼圖。其他一種方式就是用maya或3dmax先制作一張高細(xì)節(jié)網(wǎng)格,在轉(zhuǎn)為法線貼圖。這是最好的方式,但比較耗時(shí)。
法線貼圖的顏色組成范圍從0到255。當(dāng)加載貼圖到像素著色器中時(shí),該值范圍會(huì)被轉(zhuǎn)換為0到1。所以在使用法線貼圖前還需要將該值范圍轉(zhuǎn)為為-1到1,可通過將該值乘以2,再減1來實(shí)現(xiàn)。
更新常量緩沖結(jié)構(gòu)體
需要修改常量緩沖結(jié)構(gòu)體添加一個(gè)布爾變量,用來表示凹凸貼圖是否使能。這里使用的是windows布爾類型而不是標(biāo)準(zhǔn)布爾類型的,代碼如下。
struct cbPerObject {XMMATRIX WVP;XMMATRIX World;//These will be used for the pixel shaderXMFLOAT4 difColor;BOOL hasTexture;///**************new**************//Because of HLSL structure packing, we will use windows BOOL//instead of bool because HLSL packs things into 4 bytes, and//bool is only one byte, where BOOL is 4 bytesBOOL hasNormMap;///**************new************** };更新表面材質(zhì)結(jié)構(gòu)體
紋理數(shù)組中修改該結(jié)構(gòu)體以包含帶法線的圖片索引,同時(shí)也包含一個(gè)布爾值以表示法線貼圖是否使用。
struct SurfaceMaterial {std::wstring matName;XMFLOAT4 difColor;int texArrayIndex;///**************new**************int normMapTexArrayIndex;bool hasNormMap;///**************new**************bool hasTexture;bool transparent; };更新頂點(diǎn)結(jié)構(gòu)體
添加一個(gè)切線元素到頂點(diǎn)結(jié)構(gòu)體中,之后要使用頂點(diǎn)切線和法線來獲得副切線以及紋理/切線空間,以便順利轉(zhuǎn)換法線貼圖的法線。
struct Vertex {Vertex(){}Vertex(float x, float y, float z,float u, float v,float nx, float ny, float nz,float tx, float ty, float tz): pos(x,y,z), texCoord(u, v), normal(nx, ny, nz),tangent(tx, ty, tz){}XMFLOAT3 pos;XMFLOAT2 texCoord;XMFLOAT3 normal;///**************new**************XMFLOAT3 tangent;XMFLOAT3 biTangent;///**************new************** };D3D11_INPUT_ELEMENT_DESC layout[] = {{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 20, D3D11_INPUT_PER_VERTEX_DATA, 0},///**************new**************{ "TANGENT", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 32, D3D11_INPUT_PER_VERTEX_DATA, 0}///**************new************** };
更新LoadObjModel函數(shù)
修改該函數(shù)加載法線(凹凸)貼圖,隨后為每個(gè)頂點(diǎn)創(chuàng)建切線,方法和之前為每個(gè)頂點(diǎn)創(chuàng)建法線是一樣的:
bool LoadObjModel(std::wstring filename, ID3D11Buffer** vertBuff, ID3D11Buffer** indexBuff,std::vector<int>& subsetIndexStart,std::vector<int>& subsetMaterialArray,std::vector<SurfaceMaterial>& material, int& subsetCount,bool isRHCoordSys,bool computeNormals) {HRESULT hr = 0;std::wifstream fileIn (filename.c_str()); //Open filestd::wstring meshMatLib; //String to hold our obj material library filename//Arrays to store our model's informationstd::vector<DWORD> indices;std::vector<XMFLOAT3> vertPos;std::vector<XMFLOAT3> vertNorm;std::vector<XMFLOAT2> vertTexCoord;std::vector<std::wstring> meshMaterials;//Vertex definition indicesstd::vector<int> vertPosIndex;std::vector<int> vertNormIndex;std::vector<int> vertTCIndex;//Make sure we have a default if no tex coords or normals are definedbool hasTexCoord = false;bool hasNorm = false;//Temp variables to store into vectorsstd::wstring meshMaterialsTemp;int vertPosIndexTemp;int vertNormIndexTemp;int vertTCIndexTemp;wchar_t checkChar; //The variable we will use to store one char from file at a timestd::wstring face; //Holds the string containing our face verticesint vIndex = 0; //Keep track of our vertex index countint triangleCount = 0; //Total Trianglesint totalVerts = 0;int meshTriangles = 0;//Check to see if the file was openedif (fileIn){while(fileIn){ checkChar = fileIn.get(); //Get next charswitch (checkChar){ case '#':checkChar = fileIn.get();while(checkChar != '\n')checkChar = fileIn.get();break;case 'v': //Get Vertex DescriptionscheckChar = fileIn.get();if(checkChar == ' ') //v - vert position{float vz, vy, vx;fileIn >> vx >> vy >> vz; //Store the next three typesif(isRHCoordSys) //If model is from an RH Coord SystemvertPos.push_back(XMFLOAT3( vx, vy, vz * -1.0f)); //Invert the Z axiselsevertPos.push_back(XMFLOAT3( vx, vy, vz));}if(checkChar == 't') //vt - vert tex coords{ float vtcu, vtcv;fileIn >> vtcu >> vtcv; //Store next two typesif(isRHCoordSys) //If model is from an RH Coord SystemvertTexCoord.push_back(XMFLOAT2(vtcu, 1.0f-vtcv)); //Reverse the "v" axiselsevertTexCoord.push_back(XMFLOAT2(vtcu, vtcv)); hasTexCoord = true; //We know the model uses texture coords}//Since we compute the normals later, we don't need to check for normals//In the file, but i'll do it here anywayif(checkChar == 'n') //vn - vert normal{float vnx, vny, vnz;fileIn >> vnx >> vny >> vnz; //Store next three typesif(isRHCoordSys) //If model is from an RH Coord SystemvertNorm.push_back(XMFLOAT3( vnx, vny, vnz * -1.0f )); //Invert the Z axiselsevertNorm.push_back(XMFLOAT3( vnx, vny, vnz )); hasNorm = true; //We know the model defines normals}break;//New group (Subset)case 'g': //g - defines a groupcheckChar = fileIn.get();if(checkChar == ' '){subsetIndexStart.push_back(vIndex); //Start index for this subsetsubsetCount++;}break;//Get Face Indexcase 'f': //f - defines the facescheckChar = fileIn.get();if(checkChar == ' '){face = L"";std::wstring VertDef; //Holds one vertex definition at a timetriangleCount = 0;checkChar = fileIn.get();while(checkChar != '\n'){face += checkChar; //Add the char to our face stringcheckChar = fileIn.get(); //Get the next Characterif(checkChar == ' ') //If its a space...triangleCount++; //Increase our triangle count}//Check for space at the end of our face stringif(face[face.length()-1] == ' ')triangleCount--; //Each space adds to our triangle counttriangleCount -= 1; //Ever vertex in the face AFTER the first two are new facesstd::wstringstream ss(face);if(face.length() > 0){int firstVIndex, lastVIndex; //Holds the first and last vertice's indexfor(int i = 0; i < 3; ++i) //First three vertices (first triangle){ss >> VertDef; //Get vertex definition (vPos/vTexCoord/vNorm)std::wstring vertPart;int whichPart = 0; //(vPos, vTexCoord, or vNorm)//Parse this stringfor(int j = 0; j < VertDef.length(); ++j){if(VertDef[j] != '/') //If there is no divider "/", add a char to our vertPartvertPart += VertDef[j];//If the current char is a divider "/", or its the last character in the stringif(VertDef[j] == '/' || j == VertDef.length()-1){std::wistringstream wstringToInt(vertPart); //Used to convert wstring to intif(whichPart == 0) //If vPos{wstringToInt >> vertPosIndexTemp;vertPosIndexTemp -= 1; //subtract one since c++ arrays start with 0, and obj start with 1//Check to see if the vert pos was the only thing specifiedif(j == VertDef.length()-1){vertNormIndexTemp = 0;vertTCIndexTemp = 0;}}else if(whichPart == 1) //If vTexCoord{if(vertPart != L"") //Check to see if there even is a tex coord{wstringToInt >> vertTCIndexTemp;vertTCIndexTemp -= 1; //subtract one since c++ arrays start with 0, and obj start with 1}else //If there is no tex coord, make a defaultvertTCIndexTemp = 0;//If the cur. char is the second to last in the string, then//there must be no normal, so set a default normalif(j == VertDef.length()-1)vertNormIndexTemp = 0;} else if(whichPart == 2) //If vNorm{std::wistringstream wstringToInt(vertPart);wstringToInt >> vertNormIndexTemp;vertNormIndexTemp -= 1; //subtract one since c++ arrays start with 0, and obj start with 1}vertPart = L""; //Get ready for next vertex partwhichPart++; //Move on to next vertex part }}//Check to make sure there is at least one subsetif(subsetCount == 0){subsetIndexStart.push_back(vIndex); //Start index for this subsetsubsetCount++;}//Avoid duplicate verticesbool vertAlreadyExists = false;if(totalVerts >= 3) //Make sure we at least have one triangle to check{//Loop through all the verticesfor(int iCheck = 0; iCheck < totalVerts; ++iCheck){//If the vertex position and texture coordinate in memory are the same//As the vertex position and texture coordinate we just now got out//of the obj file, we will set this faces vertex index to the vertex's//index value in memory. This makes sure we don't create duplicate verticesif(vertPosIndexTemp == vertPosIndex[iCheck] && !vertAlreadyExists){if(vertTCIndexTemp == vertTCIndex[iCheck]){indices.push_back(iCheck); //Set index for this vertexvertAlreadyExists = true; //If we've made it here, the vertex already exists}}}}//If this vertex is not already in our vertex arrays, put it thereif(!vertAlreadyExists){vertPosIndex.push_back(vertPosIndexTemp);vertTCIndex.push_back(vertTCIndexTemp);vertNormIndex.push_back(vertNormIndexTemp);totalVerts++; //We created a new vertexindices.push_back(totalVerts-1); //Set index for this vertex} //If this is the very first vertex in the face, we need to//make sure the rest of the triangles use this vertexif(i == 0){firstVIndex = indices[vIndex]; //The first vertex index of this FACE}//If this was the last vertex in the first triangle, we will make sure//the next triangle uses this one (eg. tri1(1,2,3) tri2(1,3,4) tri3(1,4,5))if(i == 2){ lastVIndex = indices[vIndex]; //The last vertex index of this TRIANGLE}vIndex++; //Increment index count}meshTriangles++; //One triangle down//If there are more than three vertices in the face definition, we need to make sure//we convert the face to triangles. We created our first triangle above, now we will//create a new triangle for every new vertex in the face, using the very first vertex//of the face, and the last vertex from the triangle before the current trianglefor(int l = 0; l < triangleCount-1; ++l) //Loop through the next vertices to create new triangles{//First vertex of this triangle (the very first vertex of the face too)indices.push_back(firstVIndex); //Set index for this vertexvIndex++;//Second Vertex of this triangle (the last vertex used in the tri before this one)indices.push_back(lastVIndex); //Set index for this vertexvIndex++;//Get the third vertex for this triangless >> VertDef;std::wstring vertPart;int whichPart = 0;//Parse this string (same as above)for(int j = 0; j < VertDef.length(); ++j){if(VertDef[j] != '/')vertPart += VertDef[j];if(VertDef[j] == '/' || j == VertDef.length()-1){std::wistringstream wstringToInt(vertPart);if(whichPart == 0){wstringToInt >> vertPosIndexTemp;vertPosIndexTemp -= 1;//Check to see if the vert pos was the only thing specifiedif(j == VertDef.length()-1){vertTCIndexTemp = 0;vertNormIndexTemp = 0;}}else if(whichPart == 1){if(vertPart != L""){wstringToInt >> vertTCIndexTemp;vertTCIndexTemp -= 1;}elsevertTCIndexTemp = 0;if(j == VertDef.length()-1)vertNormIndexTemp = 0;} else if(whichPart == 2){std::wistringstream wstringToInt(vertPart);wstringToInt >> vertNormIndexTemp;vertNormIndexTemp -= 1;}vertPart = L"";whichPart++; }} //Check for duplicate verticesbool vertAlreadyExists = false;if(totalVerts >= 3) //Make sure we at least have one triangle to check{for(int iCheck = 0; iCheck < totalVerts; ++iCheck){if(vertPosIndexTemp == vertPosIndex[iCheck] && !vertAlreadyExists){if(vertTCIndexTemp == vertTCIndex[iCheck]){indices.push_back(iCheck); //Set index for this vertexvertAlreadyExists = true; //If we've made it here, the vertex already exists}}}}if(!vertAlreadyExists){vertPosIndex.push_back(vertPosIndexTemp);vertTCIndex.push_back(vertTCIndexTemp);vertNormIndex.push_back(vertNormIndexTemp);totalVerts++; //New vertex created, add to total vertsindices.push_back(totalVerts-1); //Set index for this vertex}//Set the second vertex for the next triangle to the last vertex we got lastVIndex = indices[vIndex]; //The last vertex index of this TRIANGLEmeshTriangles++; //New triangle definedvIndex++; }}}break;case 'm': //mtllib - material library filenamecheckChar = fileIn.get();if(checkChar == 't'){checkChar = fileIn.get();if(checkChar == 'l'){checkChar = fileIn.get();if(checkChar == 'l'){checkChar = fileIn.get();if(checkChar == 'i'){checkChar = fileIn.get();if(checkChar == 'b'){checkChar = fileIn.get();if(checkChar == ' '){//Store the material libraries file namefileIn >> meshMatLib;}}}}}}break;case 'u': //usemtl - which material to usecheckChar = fileIn.get();if(checkChar == 's'){checkChar = fileIn.get();if(checkChar == 'e'){checkChar = fileIn.get();if(checkChar == 'm'){checkChar = fileIn.get();if(checkChar == 't'){checkChar = fileIn.get();if(checkChar == 'l'){checkChar = fileIn.get();if(checkChar == ' '){meshMaterialsTemp = L""; //Make sure this is clearedfileIn >> meshMaterialsTemp; //Get next type (string)meshMaterials.push_back(meshMaterialsTemp);}}}}}}break;default: break;}}}else //If we could not open the file{SwapChain->SetFullscreenState(false, NULL); //Make sure we are out of fullscreen//create messagestd::wstring message = L"Could not open: ";message += filename;MessageBox(0, message.c_str(), //display messageL"Error", MB_OK);return false;}subsetIndexStart.push_back(vIndex); //There won't be another index start after our last subset, so set it here//sometimes "g" is defined at the very top of the file, then again before the first group of faces.//This makes sure the first subset does not conatain "0" indices.if(subsetIndexStart[1] == 0){subsetIndexStart.erase(subsetIndexStart.begin()+1);meshSubsets--;}//Make sure we have a default for the tex coord and normal//if one or both are not specifiedif(!hasNorm)vertNorm.push_back(XMFLOAT3(0.0f, 0.0f, 0.0f));if(!hasTexCoord)vertTexCoord.push_back(XMFLOAT2(0.0f, 0.0f));//Close the obj file, and open the mtl filefileIn.close();fileIn.open(meshMatLib.c_str());std::wstring lastStringRead;int matCount = 0; //total materials//kdset - If our diffuse color was not set, we can use the ambient color (which is usually the same)//If the diffuse color WAS set, then we don't need to set our diffuse color to ambientbool kdset = false;if (fileIn){while(fileIn){checkChar = fileIn.get(); //Get next charswitch (checkChar){//Check for commentcase '#':checkChar = fileIn.get();while(checkChar != '\n')checkChar = fileIn.get();break;//Set diffuse colorcase 'K':checkChar = fileIn.get();if(checkChar == 'd') //Diffuse Color{checkChar = fileIn.get(); //remove spacefileIn >> material[matCount-1].difColor.x;fileIn >> material[matCount-1].difColor.y;fileIn >> material[matCount-1].difColor.z;kdset = true;}//Ambient Color (We'll store it in diffuse if there isn't a diffuse already)if(checkChar == 'a') { checkChar = fileIn.get(); //remove spaceif(!kdset){fileIn >> material[matCount-1].difColor.x;fileIn >> material[matCount-1].difColor.y;fileIn >> material[matCount-1].difColor.z;}}break;//Check for transparencycase 'T':checkChar = fileIn.get();if(checkChar == 'r'){checkChar = fileIn.get(); //remove spacefloat Transparency;fileIn >> Transparency;material[matCount-1].difColor.w = Transparency;if(Transparency > 0.0f)material[matCount-1].transparent = true;}break;//Some obj files specify d for transparencycase 'd':checkChar = fileIn.get();if(checkChar == ' '){float Transparency;fileIn >> Transparency;//'d' - 0 being most transparent, and 1 being opaque, opposite of TrTransparency = 1.0f - Transparency;material[matCount-1].difColor.w = Transparency;if(Transparency > 0.0f)material[matCount-1].transparent = true; }break;//Get the diffuse map (texture)case 'm':checkChar = fileIn.get();if(checkChar == 'a'){checkChar = fileIn.get();if(checkChar == 'p'){checkChar = fileIn.get();if(checkChar == '_'){//map_Kd - Diffuse mapcheckChar = fileIn.get();if(checkChar == 'K'){checkChar = fileIn.get();if(checkChar == 'd'){std::wstring fileNamePath;fileIn.get(); //Remove whitespace between map_Kd and file//Get the file path - We read the pathname char by char since//pathnames can sometimes contain spaces, so we will read until//we find the file extensionbool texFilePathEnd = false;while(!texFilePathEnd){checkChar = fileIn.get();fileNamePath += checkChar;if(checkChar == '.'){for(int i = 0; i < 3; ++i)fileNamePath += fileIn.get();texFilePathEnd = true;} }//check if this texture has already been loadedbool alreadyLoaded = false;for(int i = 0; i < textureNameArray.size(); ++i){if(fileNamePath == textureNameArray[i]){alreadyLoaded = true;material[matCount-1].texArrayIndex = i;material[matCount-1].hasTexture = true;}}//if the texture is not already loaded, load it nowif(!alreadyLoaded){ID3D11ShaderResourceView* tempMeshSRV;hr = D3DX11CreateShaderResourceViewFromFile( d3d11Device, fileNamePath.c_str(),NULL, NULL, &tempMeshSRV, NULL );if(SUCCEEDED(hr)){textureNameArray.push_back(fileNamePath.c_str());material[matCount-1].texArrayIndex = meshSRV.size();meshSRV.push_back(tempMeshSRV);material[matCount-1].hasTexture = true;}} }}//map_d - alpha mapelse if(checkChar == 'd'){//Alpha maps are usually the same as the diffuse map//So we will assume that for now by only enabling//transparency for this material, as we will already//be using the alpha channel in the diffuse mapmaterial[matCount-1].transparent = true;}///**************new**************//map_bump - bump map (we're usinga normal map though)else if(checkChar == 'b'){checkChar = fileIn.get();if(checkChar == 'u'){checkChar = fileIn.get();if(checkChar == 'm'){checkChar = fileIn.get();if(checkChar == 'p'){std::wstring fileNamePath;fileIn.get(); //Remove whitespace between map_bump and file//Get the file path - We read the pathname char by char since//pathnames can sometimes contain spaces, so we will read until//we find the file extensionbool texFilePathEnd = false;while(!texFilePathEnd){checkChar = fileIn.get();fileNamePath += checkChar;if(checkChar == '.'){for(int i = 0; i < 3; ++i)fileNamePath += fileIn.get();texFilePathEnd = true;} }//check if this texture has already been loadedbool alreadyLoaded = false;for(int i = 0; i < textureNameArray.size(); ++i){if(fileNamePath == textureNameArray[i]){alreadyLoaded = true;material[matCount-1].normMapTexArrayIndex = i;material[matCount-1].hasNormMap = true;}}//if the texture is not already loaded, load it nowif(!alreadyLoaded){ID3D11ShaderResourceView* tempMeshSRV;hr = D3DX11CreateShaderResourceViewFromFile( d3d11Device, fileNamePath.c_str(),NULL, NULL, &tempMeshSRV, NULL );if(SUCCEEDED(hr)){textureNameArray.push_back(fileNamePath.c_str());material[matCount-1].normMapTexArrayIndex = meshSRV.size();meshSRV.push_back(tempMeshSRV);material[matCount-1].hasNormMap = true;}} }}}}///**************new**************}}}break;case 'n': //newmtl - Declare new materialcheckChar = fileIn.get();if(checkChar == 'e'){checkChar = fileIn.get();if(checkChar == 'w'){checkChar = fileIn.get();if(checkChar == 'm'){checkChar = fileIn.get();if(checkChar == 't'){checkChar = fileIn.get();if(checkChar == 'l'){checkChar = fileIn.get();if(checkChar == ' '){//New material, set its defaultsSurfaceMaterial tempMat;material.push_back(tempMat);fileIn >> material[matCount].matName;material[matCount].transparent = false;material[matCount].hasTexture = false;///**************new**************material[matCount].hasNormMap = false;material[matCount].normMapTexArrayIndex = 0;///**************new**************material[matCount].texArrayIndex = 0;matCount++;kdset = false;}}}}}}break;default:break;}}} else{SwapChain->SetFullscreenState(false, NULL); //Make sure we are out of fullscreenstd::wstring message = L"Could not open: ";message += meshMatLib;MessageBox(0, message.c_str(),L"Error", MB_OK);return false;}//Set the subsets material to the index value//of the its material in our material arrayfor(int i = 0; i < meshSubsets; ++i){bool hasMat = false;for(int j = 0; j < material.size(); ++j){if(meshMaterials[i] == material[j].matName){subsetMaterialArray.push_back(j);hasMat = true;}}if(!hasMat)subsetMaterialArray.push_back(0); //Use first material in array}std::vector<Vertex> vertices;Vertex tempVert;//Create our vertices using the information we got //from the file and store them in a vectorfor(int j = 0 ; j < totalVerts; ++j){tempVert.pos = vertPos[vertPosIndex[j]];tempVert.normal = vertNorm[vertNormIndex[j]];tempVert.texCoord = vertTexCoord[vertTCIndex[j]];vertices.push_back(tempVert);}//Compute Normals/////If computeNormals was set to true then we will create our own//normals, if it was set to false we will use the obj files normalsif(computeNormals){std::vector<XMFLOAT3> tempNormal;//normalized and unnormalized normalsXMFLOAT3 unnormalized = XMFLOAT3(0.0f, 0.0f, 0.0f);///**************new**************//tangent stuffstd::vector<XMFLOAT3> tempTangent;XMFLOAT3 tangent = XMFLOAT3(0.0f, 0.0f, 0.0f);float tcU1, tcV1, tcU2, tcV2;///**************new**************//Used to get vectors (sides) from the position of the vertsfloat vecX, vecY, vecZ;//Two edges of our triangleXMVECTOR edge1 = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f);XMVECTOR edge2 = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f);//Compute face normals//And Tangentsfor(int i = 0; i < meshTriangles; ++i){//Get the vector describing one edge of our triangle (edge 0,2)vecX = vertices[indices[(i*3)]].pos.x - vertices[indices[(i*3)+2]].pos.x;vecY = vertices[indices[(i*3)]].pos.y - vertices[indices[(i*3)+2]].pos.y;vecZ = vertices[indices[(i*3)]].pos.z - vertices[indices[(i*3)+2]].pos.z; edge1 = XMVectorSet(vecX, vecY, vecZ, 0.0f); //Create our first edge//Get the vector describing another edge of our triangle (edge 2,1)vecX = vertices[indices[(i*3)+2]].pos.x - vertices[indices[(i*3)+1]].pos.x;vecY = vertices[indices[(i*3)+2]].pos.y - vertices[indices[(i*3)+1]].pos.y;vecZ = vertices[indices[(i*3)+2]].pos.z - vertices[indices[(i*3)+1]].pos.z; edge2 = XMVectorSet(vecX, vecY, vecZ, 0.0f); //Create our second edge//Cross multiply the two edge vectors to get the un-normalized face normalXMStoreFloat3(&unnormalized, XMVector3Cross(edge1, edge2));tempNormal.push_back(unnormalized);///**************new**************//Find first texture coordinate edge 2d vectortcU1 = vertices[indices[(i*3)]].texCoord.x - vertices[indices[(i*3)+2]].texCoord.x;tcV1 = vertices[indices[(i*3)]].texCoord.y - vertices[indices[(i*3)+2]].texCoord.y;//Find second texture coordinate edge 2d vectortcU2 = vertices[indices[(i*3)+2]].texCoord.x - vertices[indices[(i*3)+1]].texCoord.x;tcV2 = vertices[indices[(i*3)+2]].texCoord.y - vertices[indices[(i*3)+1]].texCoord.y;//Find tangent using both tex coord edges and position edgestangent.x = (tcV1 * XMVectorGetX(edge1) - tcV2 * XMVectorGetX(edge2)) * (1.0f / (tcU1 * tcV2 - tcU2 * tcV1));tangent.y = (tcV1 * XMVectorGetY(edge1) - tcV2 * XMVectorGetY(edge2)) * (1.0f / (tcU1 * tcV2 - tcU2 * tcV1));tangent.z = (tcV1 * XMVectorGetZ(edge1) - tcV2 * XMVectorGetZ(edge2)) * (1.0f / (tcU1 * tcV2 - tcU2 * tcV1));tempTangent.push_back(tangent);///**************new**************}//Compute vertex normals (normal Averaging)XMVECTOR normalSum = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f);XMVECTOR tangentSum = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f);int facesUsing = 0;float tX, tY, tZ; //temp axis variables//Go through each vertexfor(int i = 0; i < totalVerts; ++i){//Check which triangles use this vertexfor(int j = 0; j < meshTriangles; ++j){if(indices[j*3] == i ||indices[(j*3)+1] == i ||indices[(j*3)+2] == i){tX = XMVectorGetX(normalSum) + tempNormal[j].x;tY = XMVectorGetY(normalSum) + tempNormal[j].y;tZ = XMVectorGetZ(normalSum) + tempNormal[j].z;normalSum = XMVectorSet(tX, tY, tZ, 0.0f); //If a face is using the vertex, add the unormalized face normal to the normalSum///**************new************** //We can reuse tX, tY, tZ to sum up tangentstX = XMVectorGetX(tangentSum) + tempTangent[j].x;tY = XMVectorGetY(tangentSum) + tempTangent[j].y;tZ = XMVectorGetZ(tangentSum) + tempTangent[j].z;tangentSum = XMVectorSet(tX, tY, tZ, 0.0f); //sum up face tangents using this vertex///**************new**************facesUsing++;}}//Get the actual normal by dividing the normalSum by the number of faces sharing the vertexnormalSum = normalSum / facesUsing;///**************new**************tangentSum = tangentSum / facesUsing;///**************new**************//Normalize the normalSum vector and tangentnormalSum = XMVector3Normalize(normalSum);///**************new**************tangentSum = XMVector3Normalize(tangentSum);///**************new**************//Store the normal and tangent in our current vertexvertices[i].normal.x = XMVectorGetX(normalSum);vertices[i].normal.y = XMVectorGetY(normalSum);vertices[i].normal.z = XMVectorGetZ(normalSum);///**************new**************vertices[i].tangent.x = XMVectorGetX(tangentSum);vertices[i].tangent.y = XMVectorGetY(tangentSum);vertices[i].tangent.z = XMVectorGetZ(tangentSum);///**************new**************//Clear normalSum, tangentSum and facesUsing for next vertexnormalSum = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f);///**************new**************tangentSum = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f);///**************new**************facesUsing = 0;}}//Create index bufferD3D11_BUFFER_DESC indexBufferDesc;ZeroMemory( &indexBufferDesc, sizeof(indexBufferDesc) );indexBufferDesc.Usage = D3D11_USAGE_DEFAULT;indexBufferDesc.ByteWidth = sizeof(DWORD) * meshTriangles*3;indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;indexBufferDesc.CPUAccessFlags = 0;indexBufferDesc.MiscFlags = 0;D3D11_SUBRESOURCE_DATA iinitData;iinitData.pSysMem = &indices[0];d3d11Device->CreateBuffer(&indexBufferDesc, &iinitData, indexBuff);//Create Vertex BufferD3D11_BUFFER_DESC vertexBufferDesc;ZeroMemory( &vertexBufferDesc, sizeof(vertexBufferDesc) );vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;vertexBufferDesc.ByteWidth = sizeof( Vertex ) * totalVerts;vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;vertexBufferDesc.CPUAccessFlags = 0;vertexBufferDesc.MiscFlags = 0;D3D11_SUBRESOURCE_DATA vertexBufferData; ZeroMemory( &vertexBufferData, sizeof(vertexBufferData) );vertexBufferData.pSysMem = &vertices[0];hr = d3d11Device->CreateBuffer( &vertexBufferDesc, &vertexBufferData, vertBuff);return true; }加載法線貼圖
在obj模型mtl文件中搜索貼圖加載時(shí),是先搜素以map_bump開頭的行,它表示的是法線貼圖凹凸感的實(shí)現(xiàn)。這與之前加載漫反射紋理是一樣的。
//map_bump - bump map (we're usinga normal map though) else if(checkChar == 'b') {checkChar = fileIn.get();if(checkChar == 'u'){checkChar = fileIn.get();if(checkChar == 'm'){checkChar = fileIn.get();if(checkChar == 'p'){std::wstring fileNamePath;fileIn.get(); //Remove whitespace between map_bump and file//Get the file path - We read the pathname char by char since//pathnames can sometimes contain spaces, so we will read until//we find the file extensionbool texFilePathEnd = false;while(!texFilePathEnd){checkChar = fileIn.get();fileNamePath += checkChar;if(checkChar == '.'){for(int i = 0; i < 3; ++i)fileNamePath += fileIn.get();texFilePathEnd = true;} }//check if this texture has already been loadedbool alreadyLoaded = false;for(int i = 0; i < textureNameArray.size(); ++i){if(fileNamePath == textureNameArray[i]){alreadyLoaded = true;material[matCount-1].normMapTexArrayIndex = i;material[matCount-1].hasNormMap = true;}}//if the texture is not already loaded, load it nowif(!alreadyLoaded){ID3D11ShaderResourceView* tempMeshSRV;hr = D3DX11CreateShaderResourceViewFromFile( d3d11Device, fileNamePath.c_str(),NULL, NULL, &tempMeshSRV, NULL );if(SUCCEEDED(hr)){textureNameArray.push_back(fileNamePath.c_str());material[matCount-1].normMapTexArrayIndex = meshSRV.size();meshSRV.push_back(tempMeshSRV);material[matCount-1].hasNormMap = true;}} }}} }創(chuàng)建一個(gè)新的材質(zhì)
當(dāng)創(chuàng)建新材質(zhì)時(shí),必須確保設(shè)置了它的默認(rèn)值來避免錯(cuò)誤或未知的結(jié)果。所以將法線貼圖索引數(shù)組設(shè)為0同時(shí)法線使能布爾值設(shè)為false。
checkChar = fileIn.get(); if(checkChar == ' ') {//New material, set its defaultsSurfaceMaterial tempMat;material.push_back(tempMat);fileIn >> material[matCount].matName;material[matCount].transparent = false;material[matCount].hasTexture = false;///**************new**************material[matCount].hasNormMap = false;material[matCount].normMapTexArrayIndex = 0;///**************new**************material[matCount].texArrayIndex = 0;matCount++;kdset = false; }計(jì)算切線
由于計(jì)算切線和計(jì)算法線算法相似,所以在這里一起做了。
首先遍歷網(wǎng)格中的每個(gè)三角形并得到它的切線。這里不深入討論數(shù)學(xué)的東西了,若有興趣可參考網(wǎng)址。在為每個(gè)三角形計(jì)算完切線后,計(jì)算所有面(共享同樣頂點(diǎn)的面)切線的平均值,法線做平均值的方法也是一樣的。
這里本來是可以定義副切線的,但是由于在像素著色器中法線是被插值到整個(gè)表面的,因此若此時(shí)在這里定義了副切線,則必須確保法線,切線和副切線都正交,這比只確保切線和法線正交后將它們?cè)俨娉双@得副切線要復(fù)雜的多。
//Compute Normals/////If computeNormals was set to true then we will create our own//normals, if it was set to false we will use the obj files normalsif(computeNormals){std::vector<XMFLOAT3> tempNormal;//normalized and unnormalized normalsXMFLOAT3 unnormalized = XMFLOAT3(0.0f, 0.0f, 0.0f);///**************new**************//tangent stuffstd::vector<XMFLOAT3> tempTangent;XMFLOAT3 tangent = XMFLOAT3(0.0f, 0.0f, 0.0f);float tcU1, tcV1, tcU2, tcV2;///**************new**************//Used to get vectors (sides) from the position of the vertsfloat vecX, vecY, vecZ;//Two edges of our triangleXMVECTOR edge1 = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f);XMVECTOR edge2 = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f);//Compute face normals//And Tangentsfor(int i = 0; i < meshTriangles; ++i){//Get the vector describing one edge of our triangle (edge 0,2)vecX = vertices[indices[(i*3)]].pos.x - vertices[indices[(i*3)+2]].pos.x;vecY = vertices[indices[(i*3)]].pos.y - vertices[indices[(i*3)+2]].pos.y;vecZ = vertices[indices[(i*3)]].pos.z - vertices[indices[(i*3)+2]].pos.z; edge1 = XMVectorSet(vecX, vecY, vecZ, 0.0f); //Create our first edge//Get the vector describing another edge of our triangle (edge 2,1)vecX = vertices[indices[(i*3)+2]].pos.x - vertices[indices[(i*3)+1]].pos.x;vecY = vertices[indices[(i*3)+2]].pos.y - vertices[indices[(i*3)+1]].pos.y;vecZ = vertices[indices[(i*3)+2]].pos.z - vertices[indices[(i*3)+1]].pos.z; edge2 = XMVectorSet(vecX, vecY, vecZ, 0.0f); //Create our second edge//Cross multiply the two edge vectors to get the un-normalized face normalXMStoreFloat3(&unnormalized, XMVector3Cross(edge1, edge2));tempNormal.push_back(unnormalized);///**************new**************//Find first texture coordinate edge 2d vectortcU1 = vertices[indices[(i*3)]].texCoord.x - vertices[indices[(i*3)+2]].texCoord.x;tcV1 = vertices[indices[(i*3)]].texCoord.y - vertices[indices[(i*3)+2]].texCoord.y;//Find second texture coordinate edge 2d vectortcU2 = vertices[indices[(i*3)+2]].texCoord.x - vertices[indices[(i*3)+1]].texCoord.x;tcV2 = vertices[indices[(i*3)+2]].texCoord.y - vertices[indices[(i*3)+1]].texCoord.y;//Find tangent using both tex coord edges and position edgestangent.x = (tcV1 * XMVectorGetX(edge1) - tcV2 * XMVectorGetX(edge2)) * (1.0f / (tcU1 * tcV2 - tcU2 * tcV1));tangent.y = (tcV1 * XMVectorGetY(edge1) - tcV2 * XMVectorGetY(edge2)) * (1.0f / (tcU1 * tcV2 - tcU2 * tcV1));tangent.z = (tcV1 * XMVectorGetZ(edge1) - tcV2 * XMVectorGetZ(edge2)) * (1.0f / (tcU1 * tcV2 - tcU2 * tcV1));tempTangent.push_back(tangent);///**************new**************}//Compute vertex normals (normal Averaging)XMVECTOR normalSum = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f);XMVECTOR tangentSum = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f);int facesUsing = 0;float tX, tY, tZ; //temp axis variables//Go through each vertexfor(int i = 0; i < totalVerts; ++i){//Check which triangles use this vertexfor(int j = 0; j < meshTriangles; ++j){if(indices[j*3] == i ||indices[(j*3)+1] == i ||indices[(j*3)+2] == i){tX = XMVectorGetX(normalSum) + tempNormal[j].x;tY = XMVectorGetY(normalSum) + tempNormal[j].y;tZ = XMVectorGetZ(normalSum) + tempNormal[j].z;normalSum = XMVectorSet(tX, tY, tZ, 0.0f); //If a face is using the vertex, add the unormalized face normal to the normalSum///**************new************** //We can reuse tX, tY, tZ to sum up tangentstX = XMVectorGetX(tangentSum) + tempTangent[j].x;tY = XMVectorGetY(tangentSum) + tempTangent[j].y;tZ = XMVectorGetZ(tangentSum) + tempTangent[j].z;tangentSum = XMVectorSet(tX, tY, tZ, 0.0f); //sum up face tangents using this vertex///**************new**************facesUsing++;}}//Get the actual normal by dividing the normalSum by the number of faces sharing the vertexnormalSum = normalSum / facesUsing;///**************new**************tangentSum = tangentSum / facesUsing;///**************new**************//Normalize the normalSum vector and tangentnormalSum = XMVector3Normalize(normalSum);///**************new**************tangentSum = XMVector3Normalize(tangentSum);///**************new**************//Store the normal and tangent in our current vertexvertices[i].normal.x = XMVectorGetX(normalSum);vertices[i].normal.y = XMVectorGetY(normalSum);vertices[i].normal.z = XMVectorGetZ(normalSum);///**************new**************vertices[i].tangent.x = XMVectorGetX(tangentSum);vertices[i].tangent.y = XMVectorGetY(tangentSum);vertices[i].tangent.z = XMVectorGetZ(tangentSum);///**************new**************//Clear normalSum, tangentSum and facesUsing for next vertexnormalSum = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f);///**************new**************tangentSum = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f);///**************new**************facesUsing = 0;}}加載ground.obj模型
使用不同于上一章節(jié)的模型,在init scene函數(shù)中修改:
if(!LoadObjModel(L"ground.obj", &meshVertBuff, &meshIndexBuff, meshSubsetIndexStart, meshSubsetTexture, material, meshSubsets, true, true))return false;繪制模型
要確保傳入布爾變量到著色器以表示法線貼圖是否使能,同時(shí)傳入的是否為法線貼圖。
之前是怎樣將漫反射紋理通過第0個(gè)槽傳入到像素著色器的,同時(shí)怎樣將法線貼圖通過第1個(gè)槽傳入的。如果通過第一個(gè)槽來發(fā)送法線貼圖,它將會(huì)保存在效果文件的漫反射變量中。
for(int i = 0; i < meshSubsets; ++i){//Set the grounds index bufferd3d11DevCon->IASetIndexBuffer( meshIndexBuff, DXGI_FORMAT_R32_UINT, 0);//Set the grounds vertex bufferd3d11DevCon->IASetVertexBuffers( 0, 1, &meshVertBuff, &stride, &offset );//Set the WVP matrix and send it to the constant buffer in effect fileWVP = meshWorld * camView * camProjection;cbPerObj.WVP = XMMatrixTranspose(WVP); cbPerObj.World = XMMatrixTranspose(meshWorld); cbPerObj.difColor = material[meshSubsetTexture[i]].difColor;cbPerObj.hasTexture = material[meshSubsetTexture[i]].hasTexture;///**************new**************cbPerObj.hasNormMap = material[meshSubsetTexture[i]].hasNormMap;///**************new**************d3d11DevCon->UpdateSubresource( cbPerObjectBuffer, 0, NULL, &cbPerObj, 0, 0 );d3d11DevCon->VSSetConstantBuffers( 0, 1, &cbPerObjectBuffer );d3d11DevCon->PSSetConstantBuffers( 1, 1, &cbPerObjectBuffer );if(material[meshSubsetTexture[i]].hasTexture)d3d11DevCon->PSSetShaderResources( 0, 1, &meshSRV[material[meshSubsetTexture[i]].texArrayIndex] );///**************new**************if(material[meshSubsetTexture[i]].hasNormMap)d3d11DevCon->PSSetShaderResources( 1, 1, &meshSRV[material[meshSubsetTexture[i]].normMapTexArrayIndex] );///**************new**************d3d11DevCon->PSSetSamplers( 0, 1, &CubesTexSamplerState );d3d11DevCon->RSSetState(RSCullNone);int indexStart = meshSubsetIndexStart[i];int indexDrawAmount = meshSubsetIndexStart[i+1] - meshSubsetIndexStart[i];if(!material[meshSubsetTexture[i]].transparent)d3d11DevCon->DrawIndexed( indexDrawAmount, indexStart, 0 );}效果文件
這里修改效果文件以實(shí)現(xiàn)真實(shí)法線貼圖。首先修改常量緩沖以保存使能凹凸貼圖的布爾變量。然后添加一個(gè)新的2d紋理,用于存儲(chǔ)法線貼圖數(shù)據(jù)。之后修改頂點(diǎn)結(jié)構(gòu)體輸出以包含法線。需要確保將切線放入到世界空間中,就像之間在法線上做的一樣。
struct Light {float3 pos;float range;float3 dir;float cone;float3 att;float4 ambient;float4 diffuse; };cbuffer cbPerFrame {Light light; };cbuffer cbPerObject {float4x4 WVP;float4x4 World;float4 difColor;bool hasTexture;bool hasNormMap; };Texture2D ObjTexture; Texture2D ObjNormMap; SamplerState ObjSamplerState; TextureCube SkyMap;struct VS_OUTPUT {float4 Pos : SV_POSITION;float4 worldPos : POSITION;float2 TexCoord : TEXCOORD;float3 normal : NORMAL;float3 tangent : TANGENT; };struct SKYMAP_VS_OUTPUT //output structure for skymap vertex shader {float4 Pos : SV_POSITION;float3 texCoord : TEXCOORD; };VS_OUTPUT VS(float4 inPos : POSITION, float2 inTexCoord : TEXCOORD, float3 normal : NORMAL, float3 tangent : TANGENT) {VS_OUTPUT output;output.Pos = mul(inPos, WVP);output.worldPos = mul(inPos, World);output.normal = mul(normal, World);output.tangent = mul(tangent, World);output.TexCoord = inTexCoord;return output; }SKYMAP_VS_OUTPUT SKYMAP_VS(float3 inPos : POSITION, float2 inTexCoord : TEXCOORD, float3 normal : NORMAL, float3 tangent : TANGENT) {SKYMAP_VS_OUTPUT output = (SKYMAP_VS_OUTPUT)0;//Set Pos to xyww instead of xyzw, so that z will always be 1 (furthest from camera)output.Pos = mul(float4(inPos, 1.0f), WVP).xyww;output.texCoord = inPos;return output; }float4 PS(VS_OUTPUT input) : SV_TARGET {input.normal = normalize(input.normal); //Set diffuse color of materialfloat4 diffuse = difColor;//If material has a diffuse texture map, set it nowif(hasTexture == true)diffuse = ObjTexture.Sample( ObjSamplerState, input.TexCoord );//If material has a normal map, we can set it nowif(hasNormMap == true){//Load normal from normal mapfloat4 normalMap = ObjNormMap.Sample( ObjSamplerState, input.TexCoord );//Change normal map range from [0, 1] to [-1, 1]normalMap = (2.0f*normalMap) - 1.0f;//Make sure tangent is completely orthogonal to normalinput.tangent = normalize(input.tangent - dot(input.tangent, input.normal)*input.normal);//Create the biTangentfloat3 biTangent = cross(input.normal, input.tangent);//Create the "Texture Space"float3x3 texSpace = float3x3(input.tangent, biTangent, input.normal);//Convert normal from normal map to texture space and store in input.normalinput.normal = normalize(mul(normalMap, texSpace));}float3 finalColor;finalColor = diffuse * light.ambient;finalColor += saturate(dot(light.dir, input.normal) * light.diffuse * diffuse);return float4(finalColor, diffuse.a); }float4 SKYMAP_PS(SKYMAP_VS_OUTPUT input) : SV_Target {return SkyMap.Sample(ObjSamplerState, input.texCoord); }float4 D2D_PS(VS_OUTPUT input) : SV_TARGET {float4 diffuse = ObjTexture.Sample( ObjSamplerState, input.TexCoord );return diffuse; }像素著色器
首先檢測(cè)法線貼圖是否在該面上使能,若沒有,則跳過,若有,則從法線貼圖中給當(dāng)前的像素加載法線,就像之前為當(dāng)前像素加載顏色一樣。該值范圍是位于0和1之間的,還需要將它轉(zhuǎn)為-1到1之間的值,因此在下一行就乘以2減去1得到該值。
下一行是確認(rèn)切線和法線為正交,通過減去切線指向法線的方向值,這將得到一個(gè)45度的角度。
現(xiàn)在正交且一切OK后,需要?jiǎng)?chuàng)建紋理空間的第三個(gè)軸:副切線。這可通過叉乘法線和切線得到。
最終,將這三個(gè)向量存進(jìn)一個(gè)3X3的矩陣中,這為該像素定義了紋理空間texSpace。
最后一步,從法線貼圖上獲得法線再乘以texSpace矩陣,并將結(jié)果保存到默認(rèn)法線變量中,這樣就可實(shí)現(xiàn)光照同時(shí)給表面一個(gè)凹凸的3d視覺感。
float4 PS(VS_OUTPUT input) : SV_TARGET {input.normal = normalize(input.normal); //Set diffuse color of materialfloat4 diffuse = difColor;//If material has a diffuse texture map, set it nowif(hasTexture == true)diffuse = ObjTexture.Sample( ObjSamplerState, input.TexCoord );//If material has a normal map, we can set it nowif(hasNormMap == true){//Load normal from normal mapfloat4 normalMap = ObjNormMap.Sample( ObjSamplerState, input.TexCoord );//Change normal map range from [0, 1] to [-1, 1]normalMap = (2.0f*normalMap) - 1.0f;//Make sure tangent is completely orthogonal to normalinput.tangent = normalize(input.tangent - dot(input.tangent, input.normal)*input.normal);//Create the biTangentfloat3 biTangent = cross(input.normal, input.tangent);//Create the "Texture Space"float3x3 texSpace = float3x3(input.tangent, biTangent, input.normal);//Convert normal from normal map to texture space and store in input.normalinput.normal = normalize(mul(normalMap, texSpace));}float3 finalColor;finalColor = diffuse * light.ambient;finalColor += saturate(dot(light.dir, input.normal) * light.diffuse * diffuse);return float4(finalColor, diffuse.a); }草地法線圖片:
草地圖片:
效果文件:
struct Light {float3 pos;float range;float3 dir;float cone;float3 att;float4 ambient;float4 diffuse; };cbuffer cbPerFrame {Light light; };cbuffer cbPerObject {float4x4 WVP;float4x4 World;float4 difColor;bool hasTexture;bool hasNormMap; };Texture2D ObjTexture; Texture2D ObjNormMap; SamplerState ObjSamplerState; TextureCube SkyMap;struct VS_OUTPUT {float4 Pos : SV_POSITION;float4 worldPos : POSITION;float2 TexCoord : TEXCOORD;float3 normal : NORMAL;float3 tangent : TANGENT; };struct SKYMAP_VS_OUTPUT //output structure for skymap vertex shader {float4 Pos : SV_POSITION;float3 texCoord : TEXCOORD; };VS_OUTPUT VS(float4 inPos : POSITION, float2 inTexCoord : TEXCOORD, float3 normal : NORMAL, float3 tangent : TANGENT) {VS_OUTPUT output;output.Pos = mul(inPos, WVP);output.worldPos = mul(inPos, World);output.normal = mul(normal, World);output.tangent = mul(tangent, World);output.TexCoord = inTexCoord;return output; }SKYMAP_VS_OUTPUT SKYMAP_VS(float3 inPos : POSITION, float2 inTexCoord : TEXCOORD, float3 normal : NORMAL, float3 tangent : TANGENT) {SKYMAP_VS_OUTPUT output = (SKYMAP_VS_OUTPUT)0;//Set Pos to xyww instead of xyzw, so that z will always be 1 (furthest from camera)output.Pos = mul(float4(inPos, 1.0f), WVP).xyww;output.texCoord = inPos;return output; }float4 PS(VS_OUTPUT input) : SV_TARGET {input.normal = normalize(input.normal);//Set diffuse color of materialfloat4 diffuse = difColor;//If material has a diffuse texture map, set it nowif(hasTexture == true)diffuse = ObjTexture.Sample( ObjSamplerState, input.TexCoord );//If material has a normal map, we can set it nowif(hasNormMap == true){//Load normal from normal mapfloat4 normalMap = ObjNormMap.Sample( ObjSamplerState, input.TexCoord );//Change normal map range from [0, 1] to [-1, 1]normalMap = (2.0f*normalMap) - 1.0f;//Make sure tangent is completely orthogonal to normalinput.tangent = normalize(input.tangent - dot(input.tangent, input.normal)*input.normal);//Create the biTangentfloat3 biTangent = cross(input.normal, input.tangent);//Create the "Texture Space"float3x3 texSpace = float3x3(input.tangent, biTangent, input.normal);//Convert normal from normal map to texture space and store in input.normalinput.normal = normalize(mul(normalMap, texSpace));}float3 finalColor;finalColor = diffuse * light.ambient;finalColor += saturate(dot(light.dir, input.normal) * light.diffuse * diffuse);return float4(finalColor, diffuse.a); }float4 SKYMAP_PS(SKYMAP_VS_OUTPUT input) : SV_Target {return SkyMap.Sample(ObjSamplerState, input.texCoord); }float4 D2D_PS(VS_OUTPUT input) : SV_TARGET {float4 diffuse = ObjTexture.Sample( ObjSamplerState, input.TexCoord );return diffuse; }實(shí)例代碼:
#include "stdafx.h" #pragma comment(lib, "d3d11.lib") #pragma comment(lib, "d3dx11.lib") #pragma comment(lib, "d3dx10.lib")#pragma comment(lib, "D3D10_1.lib") #pragma comment(lib, "DXGI.lib") #pragma comment(lib, "D2D1.lib") #pragma comment(lib, "dwrite.lib") ///**************new************** #pragma comment (lib, "dinput8.lib") #pragma comment (lib, "dxguid.lib") ///**************new**************#include <windows.h> #include "Resource.h" #include <d3d11.h> #include <d3dx11.h> #include <d3dx10.h> #include <xnamath.h> #include <D3D10_1.h> #include <DXGI.h> #include <D2D1.h> #include <sstream> #include <dwrite.h> ///**************new************** #include <dinput.h> ///**************new************** ///**************new************** #include <vector> #include <fstream> #include <istream> ///**************new************** //全局描述符 IDXGISwapChain* SwapChain; ID3D11Device* d3d11Device; ID3D11DeviceContext* d3d11DevCon; ID3D11RenderTargetView* renderTargetView;//索引緩沖 //ID3D11Buffer* squareIndexBuffer;//深度值-20170927 ID3D11DepthStencilView* depthStencilView; ID3D11Texture2D* depthStencilBuffer;//著色器 //ID3D11Buffer* squareVertBuffer; ID3D11VertexShader* VS; ID3D11PixelShader* PS; ID3D11PixelShader* D2D_PS; ID3D10Blob* VS_Buffer; ID3D10Blob* PS_Buffer; ID3D10Blob* D2D_PS_Buffer; ID3D11InputLayout* vertLayout;/// ID3D11Buffer* cbPerObjectBuffer; ID3D11BlendState* d2dTransparency; ID3D11RasterizerState* CCWcullMode; ID3D11RasterizerState* CWcullMode; //ID3D11ShaderResourceView* CubesTexture; ID3D11SamplerState* CubesTexSamplerState;ID3D11Buffer* cbPerFrameBuffer;ID3D10Device1 *d3d101Device; IDXGIKeyedMutex *keyedMutex11; IDXGIKeyedMutex *keyedMutex10; ID2D1RenderTarget *D2DRenderTarget; ID2D1SolidColorBrush *Brush; ID3D11Texture2D *BackBuffer11; ID3D11Texture2D *sharedTex11; ID3D11Buffer *d2dVertBuffer; ID3D11Buffer *d2dIndexBuffer; ID3D11ShaderResourceView *d2dTexture; IDWriteFactory *DWriteFactory; IDWriteTextFormat *TextFormat; ///**************new************** IDirectInputDevice8* DIKeyboard; IDirectInputDevice8* DIMouse; ///**************new************** ID3D11Buffer* sphereIndexBuffer; ID3D11Buffer* sphereVertBuffer;ID3D11VertexShader* SKYMAP_VS; ID3D11PixelShader* SKYMAP_PS; ID3D10Blob* SKYMAP_VS_Buffer; ID3D10Blob* SKYMAP_PS_Buffer;ID3D11ShaderResourceView* smrv;ID3D11DepthStencilState* DSLessEqual; ID3D11RasterizerState* RSCullNone; ///**************new************** ID3D11BlendState* Transparency; //網(wǎng)格變量,每個(gè)被加載的網(wǎng)格需要它自己的集 ID3D11Buffer* meshVertBuff; ID3D11Buffer* meshIndexBuff; XMMATRIX meshWorld; int meshSubsets = 0; std::vector<int> meshSubsetIndexStart; std::vector<int> meshSubsetTexture;//紋理和材質(zhì)變量,用于所有的網(wǎng)格的加載 std::vector<ID3D11ShaderResourceView*> meshSRV; std::vector<std::wstring> textureNameArray; ///**************new************** std::wstring printText; / LPCTSTR WndClassName = L"firstwindow"; HWND hwnd = NULL; HRESULT hr;const int Width = 1920; //設(shè)置寬 const int Height = 1200; // 設(shè)置高///**************new************** DIMOUSESTATE mouseLastState; LPDIRECTINPUT8 DirectInput;float rotx = 0; float rotz = 0; float scaleX = 1.0f; float scaleY = 1.0f;XMMATRIX Rotationx; //XMMATRIX Rotationy; XMMATRIX Rotationz; XMMATRIX Rotationy; ///**************new************** ///四個(gè)空間以及相機(jī)屬性 XMMATRIX WVP; //立方體 //XMMATRIX cube1World; //XMMATRIX cube2World; // //XMMATRIX World; XMMATRIX camView; XMMATRIX camProjection;XMMATRIX d2dWorld; XMVECTOR camPosition; XMVECTOR camTarget; XMVECTOR camUp; ///**************new************** XMVECTOR DefaultForward = XMVectorSet(0.0f,0.0f,1.0f, 0.0f); XMVECTOR DefaultRight = XMVectorSet(1.0f,0.0f,0.0f, 0.0f); XMVECTOR camForward = XMVectorSet(0.0f,0.0f,1.0f, 0.0f); XMVECTOR camRight = XMVectorSet(1.0f,0.0f,0.0f, 0.0f);XMMATRIX camRotationMatrix; //XMMATRIX groundWorld;float moveLeftRight = 0.0f; float moveBackForward = 0.0f;float camYaw = 0.0f; float camPitch = 0.0f; ///**************new************** int NumSphereVertices; int NumSphereFaces;XMMATRIX sphereWorld; ///**************new************** XMMATRIX Rotation; XMMATRIX Scale; XMMATRIX Translation; float rot = 0.01f;///**************new************** double countsPerSecond = 0.0; __int64 CounterStart = 0;int frameCount = 0; int fps = 0;__int64 frameTimeOld = 0; double frameTime; ///**************new************** //Function Prototypes// bool InitializeDirect3d11App(HINSTANCE hInstance); void CleanUp(); bool InitScene(); void DrawScene(); bool InitD2D_D3D101_DWrite(IDXGIAdapter1 *Adapter); void InitD2DScreenTexture(); ///**************new************** void UpdateScene(double time); ///**************new************** void UpdateCamera();void RenderText(std::wstring text, int inInt); //void RenderText(std::wstring text);void StartTimer(); double GetTime(); double GetFrameTime();// 初始化窗口 bool InitializeWindow(HINSTANCE hInstance,int ShowWnd,int width, int height,bool windowed);//初始化消息循環(huán)函數(shù) int messageloop(); //初始化窗口回調(diào)過程。Windows API是事件驅(qū)動(dòng)型的編程模型。在該函數(shù)中捕獲Windows消息,比如一個(gè)按鍵按下(也叫事件)以及程序操作流程。 ///**************new************** bool InitDirectInput(HINSTANCE hInstance); void DetectInput(double time); ///**************new************** void CreateSphere(int LatLines, int LongLines); LRESULT CALLBACK WndProc(HWND hWnd,UINT msg,WPARAM wParam,LPARAM lParam);///new //創(chuàng)建效果常量緩沖的結(jié)構(gòu)體 struct cbPerObject {XMMATRIX WVP;XMMATRIX World;///**************new**************//用于像素著色器XMFLOAT4 difColor;BOOL hasTexture;///**************new**************//Because of HLSL structure packing, we will use windows BOOL//instead of bool because HLSL packs things into 4 bytes, and//bool is only one byte, where BOOL is 4 bytesBOOL hasNormMap;///**************new************** };cbPerObject cbPerObj;///**************new************** //創(chuàng)建材質(zhì)結(jié)構(gòu)體 struct SurfaceMaterial {std::wstring matName;XMFLOAT4 difColor;int texArrayIndex;///**************new**************int normMapTexArrayIndex;bool hasNormMap;///**************new**************bool hasTexture;bool transparent; };std::vector<SurfaceMaterial> material;//自創(chuàng)建surfaceMaterial結(jié)構(gòu)體后,定義函數(shù)LoadObjModel bool LoadObjModel(std::wstring filename, //.obj filenameID3D11Buffer** vertBuff, //mesh vertex bufferID3D11Buffer** indexBuff, //mesh index bufferstd::vector<int>& subsetIndexStart, //start index of each subsetstd::vector<int>& subsetMaterialArray, //index value of material for each subsetstd::vector<SurfaceMaterial>& material, //vector of material structuresint& subsetCount, //Number of subsets in meshbool isRHCoordSys, //true if model was created in right hand coord systembool computeNormals); //true to compute the normals, false to use the files normals ///**************new************** struct Light {Light(){ZeroMemory(this, sizeof(Light));}XMFLOAT3 pos;float range;XMFLOAT3 dir;float cone;XMFLOAT3 att;float pad2;XMFLOAT4 ambient;XMFLOAT4 diffuse;}; Light light;struct cbPerFrame {Light light; };cbPerFrame constbuffPerFrame;//頂點(diǎn)結(jié)構(gòu)體以及頂點(diǎn)布局(輸入布局)struct Vertex {Vertex(){}Vertex(float x, float y, float z,float u, float v,float nx, float ny, float nz,float tx, float ty, float tz): pos(x,y,z), texCoord(u, v), normal(nx, ny, nz),tangent(tx, ty, tz){}XMFLOAT3 pos;XMFLOAT2 texCoord;XMFLOAT3 normal;///**************new**************XMFLOAT3 tangent;XMFLOAT3 biTangent;///**************new************** };D3D11_INPUT_ELEMENT_DESC layout[] = {{"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0},{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },{ "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 20, D3D11_INPUT_PER_VERTEX_DATA, 0},///**************new**************{ "TANGENT", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 32, D3D11_INPUT_PER_VERTEX_DATA, 0}///**************new************** }; UINT numElements = ARRAYSIZE(layout);//主函數(shù),傳入應(yīng)用程序句柄hInstance,前一個(gè)應(yīng)用程序句柄hPrevInstance,傳給函數(shù)處理的命令行l(wèi)pCmdLine以及窗口顯示方式的nShowCmd int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nShowCmd) {//創(chuàng)建并注冊(cè)窗口if (!InitializeWindow(hInstance, nShowCmd, Width, Height, true)){MessageBox(0, L"Window Initialization - Failed",L"Error", MB_OK);return 0;}/newif (!InitializeDirect3d11App(hInstance)) // 初始化D3D{MessageBox(0, L"Direct3D Initialization - Failed",L"Error", MB_OK);return 0;}if(!InitScene()) //Initialize our scene{MessageBox(0, L"Scene Initialization - Failed",L"Error", MB_OK);return 0;}///**************new**************if(!InitDirectInput(hInstance)){MessageBox(0, L"Direct Input Initialization - Failed",L"Error", MB_OK);return 0;}///**************new**************messageloop();CleanUp();//ReleaseObjects();return 0; } // windowed 若為true則為窗口模式顯示,若為false則為全屏模式顯示 bool InitializeWindow(HINSTANCE hInstance,int ShowWnd,int width, int height,bool windowed) {/*typedef struct _WNDCLASS{UINT cbSize;UINT style;WNDPROC lpfnWndProc;int cbClsExtra;int cbWndExtra;HANDLE hInstance;HICON hIcon;HCURSOR hCursor;HBRUSH hbrBackground;LPCTSTR lpszMenuName;LPCTSTR lpszClassName;}WNDCLASS;*/WNDCLASSEX wc;wc.cbSize = sizeof(WNDCLASSEX); //window類的大小/********windows類風(fēng)格*CS_CLASSDC 一個(gè)使用該類創(chuàng)建的在所有窗口間共享的設(shè)備上下文*CS_DBLCLKS 在窗口上使能雙擊功能*CS_HREDRAW 若窗口的寬度有改變或者窗口水平地移動(dòng),窗口將會(huì)刷新*CS_NOCLOSE 窗口菜單上禁止關(guān)閉選項(xiàng)*CS_OWNDC 為每個(gè)窗口創(chuàng)建自己的設(shè)備上下文。正好與CS_CLASSDC相反*CS_PARENTDC 這會(huì)設(shè)置創(chuàng)建的子窗口的剪裁四邊形到父窗口,這允許子窗口能夠在父窗口上繪畫*CS_VERDRAW 若在窗口的高度或窗口在垂直方向有移動(dòng)窗口會(huì)重繪**/wc.style = CS_HREDRAW | CS_VREDRAW;//lpfnWndProc是一個(gè)指向處理窗口消息函數(shù)的指針,設(shè)置窗口處理函數(shù)的函數(shù)名WndProcwc.lpfnWndProc = WndProc;//cbClsExtra是WNDCLASSEX之后額外申請(qǐng)的字節(jié)數(shù)wc.cbClsExtra = NULL;//cbWndExtra指定窗口實(shí)例之后所申請(qǐng)的字節(jié)數(shù)wc.cbWndExtra = NULL;//當(dāng)前窗口應(yīng)用程序的句柄,通過給函數(shù)GetModuleHandle()函數(shù)第一個(gè)參數(shù)傳入NULL可獲取當(dāng)前窗口應(yīng)用程序。wc.hInstance = hInstance;//hIcon用來指定窗口標(biāo)題欄左上角的圖標(biāo)。以下是一些標(biāo)準(zhǔn)圖標(biāo):/**IDI_APPLICATION 默認(rèn)應(yīng)用程序圖標(biāo)*IDI_HAND 手形狀的圖標(biāo)*IDI_EXCLAMATION 感嘆號(hào)圖標(biāo)*IDI_INFORMATION 星號(hào)圖標(biāo)*IDI_QUESTION 問號(hào)圖標(biāo)*IDI_WINLOGO 若使用的是XP則是默認(rèn)應(yīng)用程序圖標(biāo),否則是窗口logo*/wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);/*定義光標(biāo)圖標(biāo)*IDC_APPSTARTING 標(biāo)準(zhǔn)箭頭以及小型沙漏光標(biāo)*IDC_ARROW 標(biāo)準(zhǔn)箭頭光標(biāo)*IDC_CROSS 十字線光標(biāo)*IDC_HAND 手型光標(biāo)*IDC_NO 斜線圈光標(biāo)*IDC_WAIT 沙漏光標(biāo)*/wc.hCursor = LoadCursor(NULL, IDC_ARROW);//hbrBackground是一個(gè)刷子的句柄,可使得背景黑色。wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 2);//附加到窗口的菜單名字,不需要的話設(shè)置為NULLwc.lpszMenuName = NULL;//對(duì)類進(jìn)行命名wc.lpszClassName = WndClassName;//指定任務(wù)欄的圖標(biāo),使用上面的IDI_圖標(biāo)wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION);//注冊(cè)類。若失敗則會(huì)獲得一個(gè)錯(cuò)誤,若成功,則繼續(xù)創(chuàng)建窗口if (!RegisterClassEx(&wc)){MessageBox(NULL, L"Error registering class",L"Error", MB_OK | MB_ICONERROR);return 1;}//創(chuàng)建窗口hwnd = CreateWindowEx(NULL, WndClassName, L"normal mapping",WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, width,height, NULL,NULL,hInstance,NULL);if (!hwnd){MessageBox(NULL, L"Error registering class", L"Error", MB_OK | MB_ICONERROR);return 1;}//BOOL ShowWindow(HWND hWnd, int nCmdShow);//BOOL UpdateWindow(HWND hWnd);ShowWindow(hwnd, ShowWnd);UpdateWindow(hwnd);// 發(fā)送WM_PAINT消息到窗口過程,若窗口客戶區(qū)沒有任何東西要顯示,則不發(fā)送消息。返回true,繼續(xù)運(yùn)行到mainloop中去。return true; }bool InitializeDirect3d11App(HINSTANCE hInstance) {//聲明緩沖DXGI_MODE_DESC bufferDesc;ZeroMemory(&bufferDesc, sizeof(DXGI_MODE_DESC));bufferDesc.Width = Width;bufferDesc.Height = Height;bufferDesc.RefreshRate.Numerator = 60;bufferDesc.RefreshRate.Denominator = 1;bufferDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;bufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;bufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;//聲明交換鏈DXGI_SWAP_CHAIN_DESC swapChainDesc;ZeroMemory(&swapChainDesc, sizeof(DXGI_SWAP_CHAIN_DESC));swapChainDesc.BufferDesc = bufferDesc;swapChainDesc.SampleDesc.Count = 1;swapChainDesc.SampleDesc.Quality = 0;swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;swapChainDesc.BufferCount = 1;swapChainDesc.OutputWindow = hwnd;///**************new**************swapChainDesc.Windowed = true; ///**************new**************swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;//創(chuàng)建DXGI factory來枚舉顯卡IDXGIFactory1 *DXGIFactory;HRESULT hr = CreateDXGIFactory1(__uuidof(IDXGIFactory1), (void **)&DXGIFactory);//使用第一個(gè)顯卡IDXGIAdapter1 *Adapter;hr = DXGIFactory->EnumAdapters1(0, &Adapter);DXGIFactory->Release();//創(chuàng)建D3D11設(shè)備和交換鏈//hr = D3D11C//創(chuàng)建交換鏈D3D11CreateDeviceAndSwapChain(Adapter, D3D_DRIVER_TYPE_UNKNOWN, NULL, D3D11_CREATE_DEVICE_BGRA_SUPPORT, NULL, NULL, D3D11_SDK_VERSION, &swapChainDesc, &SwapChain, &d3d11Device, NULL, &d3d11DevCon);//初始化D2D D3D10.1和DirectWriteInitD2D_D3D101_DWrite(Adapter);//釋放Adapter接口Adapter->Release();//創(chuàng)建后緩沖ID3D11Texture2D* BackBuffer;SwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (void**)&BackBuffer);//創(chuàng)建渲染目標(biāo)d3d11Device->CreateRenderTargetView(BackBuffer, NULL, &renderTargetView);BackBuffer->Release();//創(chuàng)建深度模板緩沖D3D11_TEXTURE2D_DESC depthStencilDesc;depthStencilDesc.Width = Width;depthStencilDesc.Height = Height;depthStencilDesc.MipLevels = 1;depthStencilDesc.ArraySize = 1;depthStencilDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;depthStencilDesc.SampleDesc.Count = 1;depthStencilDesc.SampleDesc.Quality = 0;depthStencilDesc.Usage = D3D11_USAGE_DEFAULT;depthStencilDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL; //綁定到OMdepthStencilDesc.CPUAccessFlags = 0;depthStencilDesc.MiscFlags = 0;//創(chuàng)建深度模板視圖d3d11Device->CreateTexture2D(&depthStencilDesc, NULL, &depthStencilBuffer);d3d11Device->CreateDepthStencilView(depthStencilBuffer, NULL, &depthStencilView);return true; }bool InitD2D_D3D101_DWrite(IDXGIAdapter1 *Adapter) {//創(chuàng)建D3D101設(shè)備hr = D3D10CreateDevice1(Adapter, D3D10_DRIVER_TYPE_HARDWARE, NULL, D3D10_CREATE_DEVICE_BGRA_SUPPORT,D3D10_FEATURE_LEVEL_9_3, D3D10_1_SDK_VERSION, &d3d101Device);//創(chuàng)建共享紋理,D3D101將會(huì)渲染它D3D11_TEXTURE2D_DESC sharedTexDesc;ZeroMemory(&sharedTexDesc, sizeof(sharedTexDesc));sharedTexDesc.Width = Width;sharedTexDesc.Height = Height;sharedTexDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;// DXGI_FORMAT_R8G8B8A8_UNORM;// DXGI_FORMAT_B8G8R8A8_UNORM;sharedTexDesc.MipLevels = 1;sharedTexDesc.ArraySize = 1;sharedTexDesc.SampleDesc.Count = 1;sharedTexDesc.Usage = D3D11_USAGE_DEFAULT;sharedTexDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET;sharedTexDesc.MiscFlags = D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX;hr = d3d11Device->CreateTexture2D(&sharedTexDesc, NULL, &sharedTex11);//為共享紋理獲取key互斥量(為D3D11)hr = sharedTex11->QueryInterface(__uuidof(IDXGIKeyedMutex), (void **)&keyedMutex11);//獲取共享句柄需要在D3D10.1中打開共享紋理IDXGIResource *sharedResource10;HANDLE sharedHandle10;hr = sharedTex11->QueryInterface(__uuidof(IDXGIResource), (void **)&sharedResource10);hr = sharedResource10->GetSharedHandle(&sharedHandle10);sharedResource10->Release();//在D3D10.1中為共享紋理打開界面IDXGISurface1 *sharedSurface10;hr = d3d101Device->OpenSharedResource(sharedHandle10, __uuidof(IDXGISurface1), (void **)(&sharedSurface10));hr = sharedSurface10->QueryInterface(__uuidof(IDXGIKeyedMutex), (void **)&keyedMutex10);//創(chuàng)建D2D factoryID2D1Factory *D2DFactory;hr = D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, __uuidof(ID2D1Factory), (void **)&D2DFactory);D2D1_RENDER_TARGET_PROPERTIES renderTargetProperties;ZeroMemory(&renderTargetProperties, sizeof(renderTargetProperties));renderTargetProperties.type = D2D1_RENDER_TARGET_TYPE_HARDWARE;renderTargetProperties.pixelFormat = D2D1::PixelFormat(DXGI_FORMAT_UNKNOWN, D2D1_ALPHA_MODE_PREMULTIPLIED);hr = D2DFactory->CreateDxgiSurfaceRenderTarget(sharedSurface10, &renderTargetProperties, &D2DRenderTarget);sharedSurface10->Release();D2DFactory->Release();//創(chuàng)建立體彩色畫筆繪制一些東西hr = D2DRenderTarget->CreateSolidColorBrush(D2D1::ColorF(1.0f, 1.0f, 1.0f, 1.0f), &Brush);//DirectWritehr = DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED, __uuidof(IDWriteFactory), reinterpret_cast<IUnknown **>(&DWriteFactory));hr = DWriteFactory->CreateTextFormat(L"Script",NULL,DWRITE_FONT_WEIGHT_REGULAR,DWRITE_FONT_STYLE_NORMAL,DWRITE_FONT_STRETCH_NORMAL,24.0f,L"en-us",&TextFormat);hr = TextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING);hr = TextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR);d3d101Device->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_POINTLIST); return true; }///**************new************** bool InitDirectInput(HINSTANCE hInstance) {hr = DirectInput8Create(hInstance,DIRECTINPUT_VERSION,IID_IDirectInput8,(void**)&DirectInput,NULL); hr = DirectInput->CreateDevice(GUID_SysKeyboard,&DIKeyboard,NULL);hr = DirectInput->CreateDevice(GUID_SysMouse,&DIMouse,NULL);hr = DIKeyboard->SetDataFormat(&c_dfDIKeyboard);hr = DIKeyboard->SetCooperativeLevel(hwnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE);hr = DIMouse->SetDataFormat(&c_dfDIMouse);hr = DIMouse->SetCooperativeLevel(hwnd, DISCL_EXCLUSIVE | DISCL_NOWINKEY | DISCL_FOREGROUND);return true; }void UpdateCamera() {camRotationMatrix = XMMatrixRotationRollPitchYaw(camPitch, camYaw, 0);camTarget = XMVector3TransformCoord(DefaultForward, camRotationMatrix );camTarget = XMVector3Normalize(camTarget);XMMATRIX RotateYTempMatrix;RotateYTempMatrix = XMMatrixRotationY(camYaw);camRight = XMVector3TransformCoord(DefaultRight, RotateYTempMatrix);camUp = XMVector3TransformCoord(camUp, RotateYTempMatrix);camForward = XMVector3TransformCoord(DefaultForward, RotateYTempMatrix);camPosition += moveLeftRight*camRight;camPosition += moveBackForward*camForward;moveLeftRight = 0.0f;moveBackForward = 0.0f;camTarget = camPosition + camTarget; camView = XMMatrixLookAtLH( camPosition, camTarget, camUp ); } void DetectInput(double time) {DIMOUSESTATE mouseCurrState;BYTE keyboardState[256];DIKeyboard->Acquire();DIMouse->Acquire();DIMouse->GetDeviceState(sizeof(DIMOUSESTATE), &mouseCurrState);DIKeyboard->GetDeviceState(sizeof(keyboardState),(LPVOID)&keyboardState);if(keyboardState[DIK_ESCAPE] & 0x80)PostMessage(hwnd, WM_DESTROY, 0, 0);float speed = 10.0f * time;if(keyboardState[DIK_A] & 0x80){moveLeftRight -= speed;}if(keyboardState[DIK_D] & 0x80){moveLeftRight += speed;}if(keyboardState[DIK_W] & 0x80){moveBackForward += speed;}if(keyboardState[DIK_S] & 0x80){moveBackForward -= speed;}if((mouseCurrState.lX != mouseLastState.lX) || (mouseCurrState.lY != mouseLastState.lY)){camYaw += mouseLastState.lX * 0.001f;camPitch += mouseCurrState.lY * 0.001f;mouseLastState = mouseCurrState;}UpdateCamera();return; } ///**************new************** void CleanUp() {///**************new**************SwapChain->SetFullscreenState(false, NULL);PostMessage(hwnd, WM_DESTROY, 0, 0);///**************new**************SwapChain->Release();d3d11Device->Release();d3d11DevCon->Release();renderTargetView->Release();//squareVertBuffer->Release();//squareIndexBuffer->Release();//triangleVertBuffer->Release();VS->Release();PS->Release();VS_Buffer->Release();PS_Buffer->Release();vertLayout->Release();depthStencilView->Release();depthStencilBuffer->Release();//cbPerObjectBuffer->Release();//釋放不裁剪對(duì)象 // noCull->Release();//釋放混合對(duì)象 #if 1Transparency->Release();CCWcullMode->Release();CWcullMode->Release(); #endif //釋放線框//WireFrame->Release();d3d101Device->Release();keyedMutex11->Release();keyedMutex10->Release();D2DRenderTarget->Release();Brush->Release(); // BackBuffer11->Release();sharedTex11->Release();DWriteFactory->Release();TextFormat->Release();d2dTexture->Release();/// newcbPerFrameBuffer->Release();///**************new**************DIKeyboard->Unacquire();DIMouse->Unacquire();DirectInput->Release();sphereIndexBuffer->Release();sphereVertBuffer->Release();SKYMAP_VS->Release();SKYMAP_PS->Release();SKYMAP_VS_Buffer->Release();SKYMAP_PS_Buffer->Release();smrv->Release();DSLessEqual->Release();RSCullNone->Release();///**************new**************meshVertBuff->Release();meshIndexBuff->Release();///**************new************** }///**************new************** bool LoadObjModel(std::wstring filename, ID3D11Buffer** vertBuff, ID3D11Buffer** indexBuff,std::vector<int>& subsetIndexStart,std::vector<int>& subsetMaterialArray,std::vector<SurfaceMaterial>& material, int& subsetCount,bool isRHCoordSys,bool computeNormals) {HRESULT hr = 0;std::wifstream fileIn (filename.c_str()); //Open filestd::wstring meshMatLib; //String to hold our obj material library filename//存儲(chǔ)我們模型的信息的數(shù)組std::vector<DWORD> indices;std::vector<XMFLOAT3> vertPos;std::vector<XMFLOAT3> vertNorm;std::vector<XMFLOAT2> vertTexCoord;std::vector<std::wstring> meshMaterials;//頂點(diǎn)定義索引std::vector<int> vertPosIndex;std::vector<int> vertNormIndex;std::vector<int> vertTCIndex;//如果沒有定義紋理坐標(biāo)或發(fā)現(xiàn),確保有一個(gè)默認(rèn)的值bool hasTexCoord = false;bool hasNorm = false;//用于存儲(chǔ)向量的臨時(shí)變量std::wstring meshMaterialsTemp;int vertPosIndexTemp;int vertNormIndexTemp;int vertTCIndexTemp;wchar_t checkChar; //The variable we will use to store one char from file at a timestd::wstring face; //Holds the string containing our face verticesint vIndex = 0; //Keep track of our vertex index countint triangleCount = 0; //Total Trianglesint totalVerts = 0;int meshTriangles = 0;//檢測(cè)文件是否被打開if (fileIn){while(fileIn){ checkChar = fileIn.get(); //Get next charswitch (checkChar){ case '#':checkChar = fileIn.get();while(checkChar != '\n')checkChar = fileIn.get();break;case 'v': //獲取向量描述符checkChar = fileIn.get();if(checkChar == ' ') //v - vert position{float vz, vy, vx;fileIn >> vx >> vy >> vz; //Store the next three typesif(isRHCoordSys) //If model is from an RH Coord SystemvertPos.push_back(XMFLOAT3( vx, vy, vz * -1.0f)); //Invert the Z axiselsevertPos.push_back(XMFLOAT3( vx, vy, vz));}if(checkChar == 't') //vt - vert tex coords{ float vtcu, vtcv;fileIn >> vtcu >> vtcv; //Store next two typesif(isRHCoordSys) //If model is from an RH Coord SystemvertTexCoord.push_back(XMFLOAT2(vtcu, 1.0f-vtcv)); //Reverse the "v" axiselsevertTexCoord.push_back(XMFLOAT2(vtcu, vtcv)); hasTexCoord = true; //We know the model uses texture coords}//由于我們?cè)诤髞碛?jì)算法線,我們不必在此檢測(cè)法線//In the file, but i'll do it here anywayif(checkChar == 'n') //vn - vert normal{float vnx, vny, vnz;fileIn >> vnx >> vny >> vnz; //Store next three typesif(isRHCoordSys) //If model is from an RH Coord SystemvertNorm.push_back(XMFLOAT3( vnx, vny, vnz * -1.0f )); //Invert the Z axiselsevertNorm.push_back(XMFLOAT3( vnx, vny, vnz )); hasNorm = true; //We know the model defines normals}break;//新組(子集)case 'g': //g - defines a groupcheckChar = fileIn.get();if(checkChar == ' '){subsetIndexStart.push_back(vIndex); //Start index for this subsetsubsetCount++;}break;//獲取面索引case 'f': //f - defines the facescheckChar = fileIn.get();if(checkChar == ' '){face = L"";std::wstring VertDef; //Holds one vertex definition at a timetriangleCount = 0;checkChar = fileIn.get();while(checkChar != '\n'){face += checkChar; //Add the char to our face stringcheckChar = fileIn.get(); //Get the next Characterif(checkChar == ' ') //If its a space...triangleCount++; //Increase our triangle count}//Check for space at the end of our face stringif(face[face.length()-1] == ' ')triangleCount--; //Each space adds to our triangle counttriangleCount -= 1; //Ever vertex in the face AFTER the first two are new facesstd::wstringstream ss(face);if(face.length() > 0){int firstVIndex, lastVIndex; //Holds the first and last vertice's indexfor(int i = 0; i < 3; ++i) //First three vertices (first triangle){ss >> VertDef; //Get vertex definition (vPos/vTexCoord/vNorm)std::wstring vertPart;int whichPart = 0; //(vPos, vTexCoord, or vNorm)//Parse this stringfor(int j = 0; j < VertDef.length(); ++j){if(VertDef[j] != '/') //If there is no divider "/", add a char to our vertPartvertPart += VertDef[j];//If the current char is a divider "/", or its the last character in the stringif(VertDef[j] == '/' || j == VertDef.length()-1){std::wistringstream wstringToInt(vertPart); //Used to convert wstring to intif(whichPart == 0) //If vPos{wstringToInt >> vertPosIndexTemp;vertPosIndexTemp -= 1; //subtract one since c++ arrays start with 0, and obj start with 1//Check to see if the vert pos was the only thing specifiedif(j == VertDef.length()-1){vertNormIndexTemp = 0;vertTCIndexTemp = 0;}}else if(whichPart == 1) //If vTexCoord{if(vertPart != L"") //Check to see if there even is a tex coord{wstringToInt >> vertTCIndexTemp;vertTCIndexTemp -= 1; //subtract one since c++ arrays start with 0, and obj start with 1}else //If there is no tex coord, make a defaultvertTCIndexTemp = 0;//If the cur. char is the second to last in the string, then//there must be no normal, so set a default normalif(j == VertDef.length()-1)vertNormIndexTemp = 0;} else if(whichPart == 2) //If vNorm{std::wistringstream wstringToInt(vertPart);wstringToInt >> vertNormIndexTemp;vertNormIndexTemp -= 1; //subtract one since c++ arrays start with 0, and obj start with 1}vertPart = L""; //Get ready for next vertex partwhichPart++; //Move on to next vertex part }}//Check to make sure there is at least one subsetif(subsetCount == 0){subsetIndexStart.push_back(vIndex); //Start index for this subsetsubsetCount++;}//Avoid duplicate verticesbool vertAlreadyExists = false;if(totalVerts >= 3) //Make sure we at least have one triangle to check{//Loop through all the verticesfor(int iCheck = 0; iCheck < totalVerts; ++iCheck){//If the vertex position and texture coordinate in memory are the same//As the vertex position and texture coordinate we just now got out//of the obj file, we will set this faces vertex index to the vertex's//index value in memory. This makes sure we don't create duplicate verticesif(vertPosIndexTemp == vertPosIndex[iCheck] && !vertAlreadyExists){if(vertTCIndexTemp == vertTCIndex[iCheck]){indices.push_back(iCheck); //Set index for this vertexvertAlreadyExists = true; //If we've made it here, the vertex already exists}}}}//If this vertex is not already in our vertex arrays, put it thereif(!vertAlreadyExists){vertPosIndex.push_back(vertPosIndexTemp);vertTCIndex.push_back(vertTCIndexTemp);vertNormIndex.push_back(vertNormIndexTemp);totalVerts++; //We created a new vertexindices.push_back(totalVerts-1); //Set index for this vertex} //If this is the very first vertex in the face, we need to//make sure the rest of the triangles use this vertexif(i == 0){firstVIndex = indices[vIndex]; //The first vertex index of this FACE}//If this was the last vertex in the first triangle, we will make sure//the next triangle uses this one (eg. tri1(1,2,3) tri2(1,3,4) tri3(1,4,5))if(i == 2){ lastVIndex = indices[vIndex]; //The last vertex index of this TRIANGLE}vIndex++; //Increment index count}meshTriangles++; //One triangle down//If there are more than three vertices in the face definition, we need to make sure//we convert the face to triangles. We created our first triangle above, now we will//create a new triangle for every new vertex in the face, using the very first vertex//of the face, and the last vertex from the triangle before the current trianglefor(int l = 0; l < triangleCount-1; ++l) //Loop through the next vertices to create new triangles{//First vertex of this triangle (the very first vertex of the face too)indices.push_back(firstVIndex); //Set index for this vertexvIndex++;//Second Vertex of this triangle (the last vertex used in the tri before this one)indices.push_back(lastVIndex); //Set index for this vertexvIndex++;//Get the third vertex for this triangless >> VertDef;std::wstring vertPart;int whichPart = 0;//Parse this string (same as above)for(int j = 0; j < VertDef.length(); ++j){if(VertDef[j] != '/')vertPart += VertDef[j];if(VertDef[j] == '/' || j == VertDef.length()-1){std::wistringstream wstringToInt(vertPart);if(whichPart == 0){wstringToInt >> vertPosIndexTemp;vertPosIndexTemp -= 1;//Check to see if the vert pos was the only thing specifiedif(j == VertDef.length()-1){vertTCIndexTemp = 0;vertNormIndexTemp = 0;}}else if(whichPart == 1){if(vertPart != L""){wstringToInt >> vertTCIndexTemp;vertTCIndexTemp -= 1;}elsevertTCIndexTemp = 0;if(j == VertDef.length()-1)vertNormIndexTemp = 0;} else if(whichPart == 2){std::wistringstream wstringToInt(vertPart);wstringToInt >> vertNormIndexTemp;vertNormIndexTemp -= 1;}vertPart = L"";whichPart++; }} //Check for duplicate verticesbool vertAlreadyExists = false;if(totalVerts >= 3) //Make sure we at least have one triangle to check{for(int iCheck = 0; iCheck < totalVerts; ++iCheck){if(vertPosIndexTemp == vertPosIndex[iCheck] && !vertAlreadyExists){if(vertTCIndexTemp == vertTCIndex[iCheck]){indices.push_back(iCheck); //Set index for this vertexvertAlreadyExists = true; //If we've made it here, the vertex already exists}}}}if(!vertAlreadyExists){vertPosIndex.push_back(vertPosIndexTemp);vertTCIndex.push_back(vertTCIndexTemp);vertNormIndex.push_back(vertNormIndexTemp);totalVerts++; //New vertex created, add to total vertsindices.push_back(totalVerts-1); //Set index for this vertex}//Set the second vertex for the next triangle to the last vertex we got lastVIndex = indices[vIndex]; //The last vertex index of this TRIANGLEmeshTriangles++; //New triangle definedvIndex++; }}}break;case 'm': //mtllib - material library filenamecheckChar = fileIn.get();if(checkChar == 't'){checkChar = fileIn.get();if(checkChar == 'l'){checkChar = fileIn.get();if(checkChar == 'l'){checkChar = fileIn.get();if(checkChar == 'i'){checkChar = fileIn.get();if(checkChar == 'b'){checkChar = fileIn.get();if(checkChar == ' '){//Store the material libraries file namefileIn >> meshMatLib;}}}}}}break;case 'u': //usemtl - which material to usecheckChar = fileIn.get();if(checkChar == 's'){checkChar = fileIn.get();if(checkChar == 'e'){checkChar = fileIn.get();if(checkChar == 'm'){checkChar = fileIn.get();if(checkChar == 't'){checkChar = fileIn.get();if(checkChar == 'l'){checkChar = fileIn.get();if(checkChar == ' '){meshMaterialsTemp = L""; //Make sure this is clearedfileIn >> meshMaterialsTemp; //Get next type (string)meshMaterials.push_back(meshMaterialsTemp);}}}}}}break;default: break;}}}else //If we could not open the file{SwapChain->SetFullscreenState(false, NULL); //Make sure we are out of fullscreen//create messagestd::wstring message = L"Could not open: ";message += filename;MessageBox(0, message.c_str(), //display messageL"Error", MB_OK);return false;}subsetIndexStart.push_back(vIndex); //There won't be another index start after our last subset, so set it here//sometimes "g" is defined at the very top of the file, then again before the first group of faces.//This makes sure the first subset does not conatain "0" indices.if(subsetIndexStart[1] == 0){subsetIndexStart.erase(subsetIndexStart.begin()+1);meshSubsets--;}//Make sure we have a default for the tex coord and normal//if one or both are not specifiedif(!hasNorm)vertNorm.push_back(XMFLOAT3(0.0f, 0.0f, 0.0f));if(!hasTexCoord)vertTexCoord.push_back(XMFLOAT2(0.0f, 0.0f));//Close the obj file, and open the mtl filefileIn.close();fileIn.open(meshMatLib.c_str());std::wstring lastStringRead;int matCount = material.size(); //total materials//kdset - 若沒有設(shè)置漫反射顏色,則使用環(huán)境光顏色(通常是一樣的)//If the diffuse color WAS set, then we don't need to set our diffuse color to ambientbool kdset = false;if (fileIn){while(fileIn){checkChar = fileIn.get(); //Get next charswitch (checkChar){//Check for commentcase '#':checkChar = fileIn.get();while(checkChar != '\n')checkChar = fileIn.get();break;//Set diffuse colorcase 'K':checkChar = fileIn.get();if(checkChar == 'd') //Diffuse Color{checkChar = fileIn.get(); //remove spacefileIn >> material[matCount-1].difColor.x;fileIn >> material[matCount-1].difColor.y;fileIn >> material[matCount-1].difColor.z;kdset = true;}//Ambient Color (We'll store it in diffuse if there isn't a diffuse already)if(checkChar == 'a') { checkChar = fileIn.get(); //remove spaceif(!kdset){fileIn >> material[matCount-1].difColor.x;fileIn >> material[matCount-1].difColor.y;fileIn >> material[matCount-1].difColor.z;}}break;//Check for transparencycase 'T':checkChar = fileIn.get();if(checkChar == 'r'){checkChar = fileIn.get(); //remove spacefloat Transparency;fileIn >> Transparency;material[matCount-1].difColor.w = Transparency;if(Transparency > 0.0f)material[matCount-1].transparent = true;}break;//Some obj files specify d for transparencycase 'd':checkChar = fileIn.get();if(checkChar == ' '){float Transparency;fileIn >> Transparency;//'d' - 0 being most transparent, and 1 being opaque, opposite of TrTransparency = 1.0f - Transparency;material[matCount-1].difColor.w = Transparency;if(Transparency > 0.0f)material[matCount-1].transparent = true; }break;//Get the diffuse map (texture)case 'm':checkChar = fileIn.get();if(checkChar == 'a'){checkChar = fileIn.get();if(checkChar == 'p'){checkChar = fileIn.get();if(checkChar == '_'){//map_Kd - Diffuse mapcheckChar = fileIn.get();if(checkChar == 'K'){checkChar = fileIn.get();if(checkChar == 'd'){std::wstring fileNamePath;fileIn.get(); //Remove whitespace between map_Kd and file//Get the file path - We read the pathname char by char since//pathnames can sometimes contain spaces, so we will read until//we find the file extensionbool texFilePathEnd = false;while(!texFilePathEnd){checkChar = fileIn.get();fileNamePath += checkChar;if(checkChar == '.'){for(int i = 0; i < 3; ++i)fileNamePath += fileIn.get();texFilePathEnd = true;} }//check if this texture has already been loadedbool alreadyLoaded = false;for(int i = 0; i < textureNameArray.size(); ++i){if(fileNamePath == textureNameArray[i]){alreadyLoaded = true;material[matCount-1].texArrayIndex = i;material[matCount-1].hasTexture = true;}}//if the texture is not already loaded, load it nowif(!alreadyLoaded){ID3D11ShaderResourceView* tempMeshSRV;hr = D3DX11CreateShaderResourceViewFromFile( d3d11Device, fileNamePath.c_str(),NULL, NULL, &tempMeshSRV, NULL );if(SUCCEEDED(hr)){textureNameArray.push_back(fileNamePath.c_str());material[matCount-1].texArrayIndex = meshSRV.size();meshSRV.push_back(tempMeshSRV);material[matCount-1].hasTexture = true;}} }}//map_d - alpha mapelse if(checkChar == 'd'){//Alpha maps are usually the same as the diffuse map//So we will assume that for now by only enabling//transparency for this material, as we will already//be using the alpha channel in the diffuse mapmaterial[matCount-1].transparent = true;}///**************new**************//map_bump - bump map (we're usinga normal map though)else if(checkChar == 'b'){checkChar = fileIn.get();if(checkChar == 'u'){checkChar = fileIn.get();if(checkChar == 'm'){checkChar = fileIn.get();if(checkChar == 'p'){std::wstring fileNamePath;fileIn.get(); //Remove whitespace between map_bump and file//Get the file path - We read the pathname char by char since//pathnames can sometimes contain spaces, so we will read until//we find the file extensionbool texFilePathEnd = false;while(!texFilePathEnd){checkChar = fileIn.get();fileNamePath += checkChar;if(checkChar == '.'){for(int i = 0; i < 3; ++i)fileNamePath += fileIn.get();texFilePathEnd = true;} }//check if this texture has already been loadedbool alreadyLoaded = false;for(int i = 0; i < textureNameArray.size(); ++i){if(fileNamePath == textureNameArray[i]){alreadyLoaded = true;material[matCount-1].normMapTexArrayIndex = i;material[matCount-1].hasNormMap = true;}}//if the texture is not already loaded, load it nowif(!alreadyLoaded){ID3D11ShaderResourceView* tempMeshSRV;hr = D3DX11CreateShaderResourceViewFromFile( d3d11Device, fileNamePath.c_str(),NULL, NULL, &tempMeshSRV, NULL );if(SUCCEEDED(hr)){textureNameArray.push_back(fileNamePath.c_str());material[matCount-1].normMapTexArrayIndex = meshSRV.size();meshSRV.push_back(tempMeshSRV);material[matCount-1].hasNormMap = true;}} }}}}///**************new**************}}}break;case 'n': //newmtl - Declare new materialcheckChar = fileIn.get();if(checkChar == 'e'){checkChar = fileIn.get();if(checkChar == 'w'){checkChar = fileIn.get();if(checkChar == 'm'){checkChar = fileIn.get();if(checkChar == 't'){checkChar = fileIn.get();if(checkChar == 'l'){checkChar = fileIn.get();if(checkChar == ' '){//New material, set its defaultsSurfaceMaterial tempMat;material.push_back(tempMat);fileIn >> material[matCount].matName;material[matCount].transparent = false;material[matCount].hasTexture = false;///**************new**************material[matCount].hasNormMap = false;material[matCount].normMapTexArrayIndex = 0;///**************new**************material[matCount].texArrayIndex = 0;matCount++;kdset = false;}}}}}}break;default:break;}}} else{SwapChain->SetFullscreenState(false, NULL); //Make sure we are out of fullscreenstd::wstring message = L"Could not open: ";message += meshMatLib;MessageBox(0, message.c_str(),L"Error", MB_OK);return false;}//Set the subsets material to the index value//of the its material in our material arrayfor(int i = 0; i < meshSubsets; ++i){bool hasMat = false;for(int j = 0; j < material.size(); ++j){if(meshMaterials[i] == material[j].matName){subsetMaterialArray.push_back(j);hasMat = true;}}if(!hasMat)subsetMaterialArray.push_back(0); //Use first material in array}std::vector<Vertex> vertices;Vertex tempVert;//Create our vertices using the information we got //from the file and store them in a vectorfor(int j = 0 ; j < totalVerts; ++j){tempVert.pos = vertPos[vertPosIndex[j]];tempVert.normal = vertNorm[vertNormIndex[j]];tempVert.texCoord = vertTexCoord[vertTCIndex[j]];vertices.push_back(tempVert);}//Compute Normals/////If computeNormals was set to true then we will create our own//normals, if it was set to false we will use the obj files normalsif(computeNormals){std::vector<XMFLOAT3> tempNormal;//normalized and unnormalized normalsXMFLOAT3 unnormalized = XMFLOAT3(0.0f, 0.0f, 0.0f);///**************new**************//tangent stuffstd::vector<XMFLOAT3> tempTangent;XMFLOAT3 tangent = XMFLOAT3(0.0f, 0.0f, 0.0f);float tcU1, tcV1, tcU2, tcV2;///**************new**************//Used to get vectors (sides) from the position of the vertsfloat vecX, vecY, vecZ;//Two edges of our triangleXMVECTOR edge1 = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f);XMVECTOR edge2 = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f);//Compute face normalsfor(int i = 0; i < meshTriangles; ++i){//Get the vector describing one edge of our triangle (edge 0,2)vecX = vertices[indices[(i*3)]].pos.x - vertices[indices[(i*3)+2]].pos.x;vecY = vertices[indices[(i*3)]].pos.y - vertices[indices[(i*3)+2]].pos.y;vecZ = vertices[indices[(i*3)]].pos.z - vertices[indices[(i*3)+2]].pos.z; edge1 = XMVectorSet(vecX, vecY, vecZ, 0.0f); //Create our first edge//Get the vector describing another edge of our triangle (edge 2,1)vecX = vertices[indices[(i*3)+2]].pos.x - vertices[indices[(i*3)+1]].pos.x;vecY = vertices[indices[(i*3)+2]].pos.y - vertices[indices[(i*3)+1]].pos.y;vecZ = vertices[indices[(i*3)+2]].pos.z - vertices[indices[(i*3)+1]].pos.z; edge2 = XMVectorSet(vecX, vecY, vecZ, 0.0f); //Create our second edge//Cross multiply the two edge vectors to get the un-normalized face normalXMStoreFloat3(&unnormalized, XMVector3Cross(edge1, edge2));tempNormal.push_back(unnormalized);///**************new**************//Find first texture coordinate edge 2d vectortcU1 = vertices[indices[(i*3)]].texCoord.x - vertices[indices[(i*3)+2]].texCoord.x;tcV1 = vertices[indices[(i*3)]].texCoord.y - vertices[indices[(i*3)+2]].texCoord.y;//Find second texture coordinate edge 2d vectortcU2 = vertices[indices[(i*3)+2]].texCoord.x - vertices[indices[(i*3)+1]].texCoord.x;tcV2 = vertices[indices[(i*3)+2]].texCoord.y - vertices[indices[(i*3)+1]].texCoord.y;//Find tangent using both tex coord edges and position edgestangent.x = (tcV1 * XMVectorGetX(edge1) - tcV2 * XMVectorGetX(edge2)) * (1.0f / (tcU1 * tcV2 - tcU2 * tcV1));tangent.y = (tcV1 * XMVectorGetY(edge1) - tcV2 * XMVectorGetY(edge2)) * (1.0f / (tcU1 * tcV2 - tcU2 * tcV1));tangent.z = (tcV1 * XMVectorGetZ(edge1) - tcV2 * XMVectorGetZ(edge2)) * (1.0f / (tcU1 * tcV2 - tcU2 * tcV1));tempTangent.push_back(tangent);///**************new**************}//Compute vertex normals (normal Averaging)XMVECTOR normalSum = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f);XMVECTOR tangentSum = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f);int facesUsing = 0;float tX, tY, tZ; //temp axis variables//Go through each vertexfor(int i = 0; i < totalVerts; ++i){//Check which triangles use this vertexfor(int j = 0; j < meshTriangles; ++j){if(indices[j*3] == i ||indices[(j*3)+1] == i ||indices[(j*3)+2] == i){tX = XMVectorGetX(normalSum) + tempNormal[j].x;tY = XMVectorGetY(normalSum) + tempNormal[j].y;tZ = XMVectorGetZ(normalSum) + tempNormal[j].z;normalSum = XMVectorSet(tX, tY, tZ, 0.0f); //If a face is using the vertex, add the unormalized face normal to the normalSum///**************new************** //We can reuse tX, tY, tZ to sum up tangentstX = XMVectorGetX(tangentSum) + tempTangent[j].x;tY = XMVectorGetY(tangentSum) + tempTangent[j].y;tZ = XMVectorGetZ(tangentSum) + tempTangent[j].z;tangentSum = XMVectorSet(tX, tY, tZ, 0.0f); //sum up face tangents using this vertex///**************new**************facesUsing++;}}//Get the actual normal by dividing the normalSum by the number of faces sharing the vertexnormalSum = normalSum / facesUsing;///**************new**************tangentSum = tangentSum / facesUsing;///**************new**************//Normalize the normalSum vectornormalSum = XMVector3Normalize(normalSum);///**************new**************tangentSum = XMVector3Normalize(tangentSum);///**************new**************//Store the normal in our current vertexvertices[i].normal.x = XMVectorGetX(normalSum);vertices[i].normal.y = XMVectorGetY(normalSum);vertices[i].normal.z = XMVectorGetZ(normalSum);///**************new**************vertices[i].tangent.x = XMVectorGetX(tangentSum);vertices[i].tangent.y = XMVectorGetY(tangentSum);vertices[i].tangent.z = XMVectorGetZ(tangentSum);///**************new**************//Clear normalSum and facesUsing for next vertexnormalSum = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f);///**************new**************tangentSum = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f);///**************new**************facesUsing = 0;}}//Create index bufferD3D11_BUFFER_DESC indexBufferDesc;ZeroMemory( &indexBufferDesc, sizeof(indexBufferDesc) );indexBufferDesc.Usage = D3D11_USAGE_DEFAULT;indexBufferDesc.ByteWidth = sizeof(DWORD) * meshTriangles*3;indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;indexBufferDesc.CPUAccessFlags = 0;indexBufferDesc.MiscFlags = 0;D3D11_SUBRESOURCE_DATA iinitData;iinitData.pSysMem = &indices[0];d3d11Device->CreateBuffer(&indexBufferDesc, &iinitData, indexBuff);//Create Vertex BufferD3D11_BUFFER_DESC vertexBufferDesc;ZeroMemory( &vertexBufferDesc, sizeof(vertexBufferDesc) );vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;vertexBufferDesc.ByteWidth = sizeof( Vertex ) * totalVerts;vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;vertexBufferDesc.CPUAccessFlags = 0;vertexBufferDesc.MiscFlags = 0;D3D11_SUBRESOURCE_DATA vertexBufferData; ZeroMemory( &vertexBufferData, sizeof(vertexBufferData) );vertexBufferData.pSysMem = &vertices[0];hr = d3d11Device->CreateBuffer( &vertexBufferDesc, &vertexBufferData, vertBuff);return true; } ///**************new**************void CreateSphere(int LatLines, int LongLines) {NumSphereVertices = ((LatLines-2) * LongLines) + 2;NumSphereFaces = ((LatLines-3)*(LongLines)*2) + (LongLines*2);float sphereYaw = 0.0f;float spherePitch = 0.0f;std::vector<Vertex> vertices(NumSphereVertices);XMVECTOR currVertPos = XMVectorSet(0.0f, 0.0f, 1.0f, 0.0f);vertices[0].pos.x = 0.0f;vertices[0].pos.y = 0.0f;vertices[0].pos.z = 1.0f;for(DWORD i = 0; i < LatLines-2; ++i){spherePitch = (i+1) * (3.14f/(LatLines-1));Rotationx = XMMatrixRotationX(spherePitch);for(DWORD j = 0; j < LongLines; ++j){sphereYaw = j * (6.28f/(LongLines));Rotationy = XMMatrixRotationZ(sphereYaw);currVertPos = XMVector3TransformNormal( XMVectorSet(0.0f, 0.0f, 1.0f, 0.0f), (Rotationx * Rotationy) ); currVertPos = XMVector3Normalize( currVertPos );vertices[i*LongLines+j+1].pos.x = XMVectorGetX(currVertPos);vertices[i*LongLines+j+1].pos.y = XMVectorGetY(currVertPos);vertices[i*LongLines+j+1].pos.z = XMVectorGetZ(currVertPos);}}vertices[NumSphereVertices-1].pos.x = 0.0f;vertices[NumSphereVertices-1].pos.y = 0.0f;vertices[NumSphereVertices-1].pos.z = -1.0f;D3D11_BUFFER_DESC vertexBufferDesc;ZeroMemory( &vertexBufferDesc, sizeof(vertexBufferDesc) );vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;vertexBufferDesc.ByteWidth = sizeof( Vertex ) * NumSphereVertices;vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;vertexBufferDesc.CPUAccessFlags = 0;vertexBufferDesc.MiscFlags = 0;D3D11_SUBRESOURCE_DATA vertexBufferData; ZeroMemory( &vertexBufferData, sizeof(vertexBufferData) );vertexBufferData.pSysMem = &vertices[0];hr = d3d11Device->CreateBuffer( &vertexBufferDesc, &vertexBufferData, &sphereVertBuffer);std::vector<DWORD> indices(NumSphereFaces * 3);int k = 0;for(DWORD l = 0; l < LongLines-1; ++l){indices[k] = 0;indices[k+1] = l+1;indices[k+2] = l+2;k += 3;}indices[k] = 0;indices[k+1] = LongLines;indices[k+2] = 1;k += 3;for(DWORD i = 0; i < LatLines-3; ++i){for(DWORD j = 0; j < LongLines-1; ++j){indices[k] = i*LongLines+j+1;indices[k+1] = i*LongLines+j+2;indices[k+2] = (i+1)*LongLines+j+1;indices[k+3] = (i+1)*LongLines+j+1;indices[k+4] = i*LongLines+j+2;indices[k+5] = (i+1)*LongLines+j+2;k += 6; // next quad}indices[k] = (i*LongLines)+LongLines;indices[k+1] = (i*LongLines)+1;indices[k+2] = ((i+1)*LongLines)+LongLines;indices[k+3] = ((i+1)*LongLines)+LongLines;indices[k+4] = (i*LongLines)+1;indices[k+5] = ((i+1)*LongLines)+1;k += 6;}for(DWORD l = 0; l < LongLines-1; ++l){indices[k] = NumSphereVertices-1;indices[k+1] = (NumSphereVertices-1)-(l+1);indices[k+2] = (NumSphereVertices-1)-(l+2);k += 3;}indices[k] = NumSphereVertices-1;indices[k+1] = (NumSphereVertices-1)-LongLines;indices[k+2] = NumSphereVertices-2;D3D11_BUFFER_DESC indexBufferDesc;ZeroMemory( &indexBufferDesc, sizeof(indexBufferDesc) );indexBufferDesc.Usage = D3D11_USAGE_DEFAULT;indexBufferDesc.ByteWidth = sizeof(DWORD) * NumSphereFaces * 3;indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;indexBufferDesc.CPUAccessFlags = 0;indexBufferDesc.MiscFlags = 0;D3D11_SUBRESOURCE_DATA iinitData;iinitData.pSysMem = &indices[0];d3d11Device->CreateBuffer(&indexBufferDesc, &iinitData, &sphereIndexBuffer);} void InitD2DScreenTexture() {//創(chuàng)建頂點(diǎn)緩沖Vertex v[] ={// Front FaceVertex(-1.0f, -1.0f, -1.0f, 0.0f, 1.0f,-1.0f, -1.0f, -1.0f, 0.0f, 0.0f, 0.0f),Vertex(-1.0f, 1.0f, -1.0f, 0.0f, 0.0f,-1.0f, 1.0f, -1.0f, 0.0f, 0.0f, 0.0f),Vertex( 1.0f, 1.0f, -1.0f, 1.0f, 0.0f, 1.0f, 1.0f, -1.0f, 0.0f, 0.0f, 0.0f),Vertex( 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 0.0f, 0.0f, 0.0f),};DWORD indices[] = {//字體面0, 1, 2,0, 2, 3,};D3D11_BUFFER_DESC indexBufferDesc;ZeroMemory(&indexBufferDesc, sizeof(indexBufferDesc));indexBufferDesc.Usage = D3D11_USAGE_DEFAULT;indexBufferDesc.ByteWidth = sizeof(DWORD) * 2 * 3;indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;indexBufferDesc.CPUAccessFlags = 0;indexBufferDesc.MiscFlags = 0;D3D11_SUBRESOURCE_DATA iinitData;iinitData.pSysMem = indices;d3d11Device->CreateBuffer(&indexBufferDesc, &iinitData, &d2dIndexBuffer);D3D11_BUFFER_DESC vertexBufferDesc;ZeroMemory(&vertexBufferDesc, sizeof(vertexBufferDesc));vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;vertexBufferDesc.ByteWidth = sizeof(Vertex) * 4;vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;vertexBufferDesc.CPUAccessFlags = 0;vertexBufferDesc.MiscFlags = 0;D3D11_SUBRESOURCE_DATA vertexBufferData;ZeroMemory(&vertexBufferData, sizeof(vertexBufferData));vertexBufferData.pSysMem = v;hr = d3d11Device->CreateBuffer(&vertexBufferDesc, &vertexBufferData, &d2dVertBuffer);//從紋理D2D,創(chuàng)建一個(gè)著色器資源視圖//因此,能夠使用它來創(chuàng)建一個(gè)矩形紋理,用于覆蓋場(chǎng)景d3d11Device->CreateShaderResourceView(sharedTex11, NULL, &d2dTexture);}//void ReleaseObjects() //{ //釋放創(chuàng)建的COM對(duì)象 // SwapChain->Release(); // d3d11Device->Release(); // d3d11DevCon->Release(); //}bool InitScene() {//InitD2DScreenTexture();//編譯著色器CreateSphere(10, 10);///**************new**************if(!LoadObjModel(L"ground.obj", &meshVertBuff, &meshIndexBuff, meshSubsetIndexStart, meshSubsetTexture, material, meshSubsets, true, true))return false;///**************new**************///**************new**************hr = D3DX11CompileFromFile(L"Effects.fx", 0, 0, "VS", "vs_4_0", 0, 0, 0, &VS_Buffer, 0, 0);hr = D3DX11CompileFromFile(L"Effects.fx", 0, 0, "PS", "ps_4_0", 0, 0, 0, &PS_Buffer, 0, 0);/// newhr = D3DX11CompileFromFile(L"Effects.fx", 0, 0, "D2D_PS", "ps_4_0", 0, 0, 0, &D2D_PS_Buffer, 0, 0);hr = D3DX11CompileFromFile(L"Effects.fx", 0, 0, "SKYMAP_VS", "vs_4_0", 0, 0, 0, &SKYMAP_VS_Buffer, 0, 0);hr = D3DX11CompileFromFile(L"Effects.fx", 0, 0, "SKYMAP_PS", "ps_4_0", 0, 0, 0, &SKYMAP_PS_Buffer, 0, 0);///**************new**************//創(chuàng)建著色器對(duì)象hr = d3d11Device->CreateVertexShader(VS_Buffer->GetBufferPointer(), VS_Buffer->GetBufferSize(), NULL, &VS);hr = d3d11Device->CreatePixelShader(PS_Buffer->GetBufferPointer(), PS_Buffer->GetBufferSize(), NULL, &PS);///newhr = d3d11Device->CreatePixelShader(D2D_PS_Buffer->GetBufferPointer(), D2D_PS_Buffer->GetBufferSize(), NULL, &D2D_PS);hr = d3d11Device->CreateVertexShader(SKYMAP_VS_Buffer->GetBufferPointer(), SKYMAP_VS_Buffer->GetBufferSize(), NULL, &SKYMAP_VS);hr = d3d11Device->CreatePixelShader(SKYMAP_PS_Buffer->GetBufferPointer(), SKYMAP_PS_Buffer->GetBufferSize(), NULL, &SKYMAP_PS);///**************new**************///**************new**************//設(shè)置頂點(diǎn)和像素著色器d3d11DevCon->VSSetShader(VS, 0, 0);d3d11DevCon->PSSetShader(PS, 0, 0);///**************new**************light.pos = XMFLOAT3(0.0f, 7.0f, 0.0f);light.dir = XMFLOAT3(0.5f, 0.75f, -0.5f);light.range = 1000.0f;light.cone = 12.0f;light.att = XMFLOAT3(0.4f, 0.02f, 0.000f);light.ambient = XMFLOAT4(0.2f, 0.2f, 0.2f, 1.0f);light.diffuse = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f);//Create the Input Layout//創(chuàng)建輸入布局d3d11Device->CreateInputLayout(layout, numElements, VS_Buffer->GetBufferPointer(),VS_Buffer->GetBufferSize(), &vertLayout);//設(shè)置輸入布局d3d11DevCon->IASetInputLayout(vertLayout);//設(shè)置圖元拓?fù)鋎3d11DevCon->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);//創(chuàng)建視口D3D11_VIEWPORT viewport;ZeroMemory(&viewport, sizeof(D3D11_VIEWPORT));viewport.TopLeftX = 0;viewport.TopLeftY = 0;viewport.Width = Width;viewport.Height = Height;viewport.MinDepth = 0.0f;viewport.MaxDepth = 1.0f;//設(shè)置視口d3d11DevCon->RSSetViewports(1, &viewport);//創(chuàng)建緩沖用來發(fā)送到效果文件的cbufferD3D11_BUFFER_DESC cbbd;ZeroMemory(&cbbd, sizeof(D3D11_BUFFER_DESC));cbbd.Usage = D3D11_USAGE_DEFAULT;cbbd.ByteWidth = sizeof(cbPerObject);cbbd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;cbbd.CPUAccessFlags = 0;cbbd.MiscFlags = 0;hr = d3d11Device->CreateBuffer(&cbbd, NULL, &cbPerObjectBuffer);//創(chuàng)建緩沖用于每幀發(fā)送cbuffer到著色器文件ZeroMemory(&cbbd, sizeof(D3D11_BUFFER_DESC));cbbd.Usage = D3D11_USAGE_DEFAULT;cbbd.ByteWidth = sizeof(cbPerFrame);cbbd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;cbbd.CPUAccessFlags = 0;cbbd.MiscFlags = 0;d3d11Device->CreateBuffer(&cbbd, NULL, &cbPerFrameBuffer);//相機(jī)信息//相機(jī)信息camPosition = XMVectorSet( 0.0f, 5.0f, -8.0f, 0.0f );//camPosition = XMVectorSet(0.0f, 0.0f, -0.5f, 0.0f);camTarget = XMVectorSet( 0.0f, 0.5f, 0.0f, 0.0f );camUp = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);//設(shè)置視圖矩陣camView = XMMatrixLookAtLH(camPosition, camTarget, camUp);//設(shè)置投影矩陣camProjection = XMMatrixPerspectiveFovLH(0.4f*3.14f, (float)Width / Height, 1.0f, 1000.0f);D3D11_BLEND_DESC blendDesc;ZeroMemory( &blendDesc, sizeof(blendDesc) );D3D11_RENDER_TARGET_BLEND_DESC rtbd;ZeroMemory( &rtbd, sizeof(rtbd) );rtbd.BlendEnable = true;rtbd.SrcBlend = D3D11_BLEND_SRC_COLOR;///**************new**************rtbd.DestBlend = D3D11_BLEND_INV_SRC_ALPHA;///**************new**************rtbd.BlendOp = D3D11_BLEND_OP_ADD;rtbd.SrcBlendAlpha = D3D11_BLEND_ONE;rtbd.DestBlendAlpha = D3D11_BLEND_ZERO;rtbd.BlendOpAlpha = D3D11_BLEND_OP_ADD;rtbd.RenderTargetWriteMask = D3D10_COLOR_WRITE_ENABLE_ALL;blendDesc.AlphaToCoverageEnable = false;blendDesc.RenderTarget[0] = rtbd;d3d11Device->CreateBlendState(&blendDesc, &d2dTransparency);///**************new**************ZeroMemory( &rtbd, sizeof(rtbd) );rtbd.BlendEnable = true;rtbd.SrcBlend = D3D11_BLEND_INV_SRC_ALPHA;rtbd.DestBlend = D3D11_BLEND_SRC_ALPHA;rtbd.BlendOp = D3D11_BLEND_OP_ADD;rtbd.SrcBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA;rtbd.DestBlendAlpha = D3D11_BLEND_SRC_ALPHA;rtbd.BlendOpAlpha = D3D11_BLEND_OP_ADD;rtbd.RenderTargetWriteMask = D3D10_COLOR_WRITE_ENABLE_ALL;blendDesc.AlphaToCoverageEnable = false;blendDesc.RenderTarget[0] = rtbd;d3d11Device->CreateBlendState(&blendDesc, &Transparency);///**************new**************//加載圖像紋理//hr = //#if 1 // hr = D3DX11CreateShaderResourceViewFromFile(d3d11Device, L"grass.jpg", // NULL, NULL, &CubesTexture, NULL); #if 1///**************new**************//告訴D3D我們正在加載一個(gè)立方體紋理D3DX11_IMAGE_LOAD_INFO loadSMInfo;loadSMInfo.MiscFlags = D3D11_RESOURCE_MISC_TEXTURECUBE;//加載紋理ID3D11Texture2D* SMTexture = 0;hr = D3DX11CreateTextureFromFile(d3d11Device, L"skymap.dds",&loadSMInfo, 0, (ID3D11Resource**)&SMTexture, 0);//創(chuàng)建紋理描述符D3D11_TEXTURE2D_DESC SMTextureDesc;SMTexture->GetDesc(&SMTextureDesc);//告訴D3D我們有一個(gè)立方體紋理,它是一個(gè)2D紋理的數(shù)組D3D11_SHADER_RESOURCE_VIEW_DESC SMViewDesc;SMViewDesc.Format = SMTextureDesc.Format;SMViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBE;SMViewDesc.TextureCube.MipLevels = SMTextureDesc.MipLevels;SMViewDesc.TextureCube.MostDetailedMip = 0;//創(chuàng)建資源視圖hr = d3d11Device->CreateShaderResourceView(SMTexture, &SMViewDesc, &smrv);///**************new************** #endif//配置采樣狀態(tài)D3D11_SAMPLER_DESC sampDesc;ZeroMemory(&sampDesc, sizeof(sampDesc));sampDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;sampDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;sampDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;sampDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;sampDesc.ComparisonFunc = D3D11_COMPARISON_NEVER;sampDesc.MinLOD = 0;sampDesc.MaxLOD = D3D11_FLOAT32_MAX;//創(chuàng)建采樣狀態(tài)hr = d3d11Device->CreateSamplerState(&sampDesc, &CubesTexSamplerState);//d3d11Device->CreateBlendState(&blendDesc, &Transparency);//創(chuàng)建逆時(shí)針和順時(shí)針狀態(tài)D3D11_RASTERIZER_DESC cmdesc;ZeroMemory(&cmdesc, sizeof(D3D11_RASTERIZER_DESC));cmdesc.FillMode = D3D11_FILL_SOLID;cmdesc.CullMode = D3D11_CULL_BACK;cmdesc.FrontCounterClockwise = true;hr = d3d11Device->CreateRasterizerState(&cmdesc, &CCWcullMode);cmdesc.FrontCounterClockwise = false;hr = d3d11Device->CreateRasterizerState(&cmdesc, &CWcullMode); #if 1///**************new**************cmdesc.CullMode = D3D11_CULL_NONE;hr = d3d11Device->CreateRasterizerState(&cmdesc, &RSCullNone);D3D11_DEPTH_STENCIL_DESC dssDesc;ZeroMemory(&dssDesc, sizeof(D3D11_DEPTH_STENCIL_DESC));dssDesc.DepthEnable = true;dssDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;dssDesc.DepthFunc = D3D11_COMPARISON_LESS_EQUAL;d3d11Device->CreateDepthStencilState(&dssDesc, &DSLessEqual);///**************new************** #endifreturn true; }///**************new************** void StartTimer() {LARGE_INTEGER frequencyCount;QueryPerformanceFrequency(&frequencyCount);countsPerSecond = double(frequencyCount.QuadPart);QueryPerformanceCounter(&frequencyCount);CounterStart = frequencyCount.QuadPart; }double GetTime() {LARGE_INTEGER currentTime;QueryPerformanceCounter(¤tTime);return double(currentTime.QuadPart-CounterStart)/countsPerSecond; }double GetFrameTime() {LARGE_INTEGER currentTime;__int64 tickCount;QueryPerformanceCounter(¤tTime);tickCount = currentTime.QuadPart-frameTimeOld;frameTimeOld = currentTime.QuadPart;if(tickCount < 0.0f)tickCount = 0.0f;return float(tickCount)/countsPerSecond; } ///**************new**************///**************new************** void UpdateScene(double time)///**************new************** //void UpdateScene() {//Reset cube1World // groundWorld = XMMatrixIdentity();//Define cube1's world space matrix///**************new************** // Scale = XMMatrixScaling( 500.0f, 10.0f, 500.0f ); // Translation = XMMatrixTranslation( 0.0f, 10.0f, 0.0f );//Set cube1's world space using the transformations // groundWorld = Scale * Translation;//復(fù)位球面世界sphereWorld = XMMatrixIdentity();//Define sphereWorld's world space matrixScale = XMMatrixScaling( 5.0f, 5.0f, 5.0f );//Make sure the sphere is always centered around cameraTranslation = XMMatrixTranslation( XMVectorGetX(camPosition), XMVectorGetY(camPosition), XMVectorGetZ(camPosition) );//Set sphereWorld's world space using the transformationssphereWorld = Scale * Translation;///**************new**************meshWorld = XMMatrixIdentity();//Define cube1's world space matrixRotation = XMMatrixRotationY(3.14f);Scale = XMMatrixScaling( 1.0f, 1.0f, 1.0f );Translation = XMMatrixTranslation( 0.0f, 0.0f, 0.0f );meshWorld = Rotation * Scale * Translation;///**************new**************///**************new************** // light.pos.x = XMVectorGetX(camPosition); // light.pos.y = XMVectorGetY(camPosition); // light.pos.z = XMVectorGetZ(camPosition);// light.dir.x = XMVectorGetX(camTarget) - light.pos.x; // light.dir.y = XMVectorGetY(camTarget) - light.pos.y; // light.dir.z = XMVectorGetZ(camTarget) - light.pos.z;///**************new************** }///**************new************** void RenderText(std::wstring text, int inInt) //void RenderText(std::wstring text) {//釋放D3D11設(shè)備d3d11DevCon->PSSetShader(D2D_PS, 0, 0);keyedMutex11->ReleaseSync(0);//使用D3D10.1設(shè)備keyedMutex10->AcquireSync(0, 5);//繪制D2D內(nèi)容D2DRenderTarget->BeginDraw();//清空D2D背景色D2DRenderTarget->Clear(D2D1::ColorF(0.0f, 0.0f, 0.0f, 0.0f));//創(chuàng)建字符串std::wostringstream printString;///**************new**************printString << text << inInt;// printString << text;///**************new**************printText = printString.str();//設(shè)置字體顏色D2D1_COLOR_F FontColor = D2D1::ColorF(1.0f, 1.0f, 1.0f, 1.0f);//設(shè)置D2D繪制要用到的畫筆顏色Brush->SetColor(FontColor);//創(chuàng)建D2D渲染區(qū)域D2D1_RECT_F layoutRect = D2D1::RectF(0, 0, Width, Height);//繪制文本D2DRenderTarget->DrawText(printText.c_str(),wcslen(printText.c_str()),TextFormat,layoutRect,Brush);D2DRenderTarget->EndDraw();//釋放D3D10.1設(shè)備keyedMutex10->ReleaseSync(1);//使用D3D11設(shè)備keyedMutex11->AcquireSync(1, 5);//使用著色器資源表示d2d渲染目標(biāo)來創(chuàng)建一個(gè)矩形紋理,該矩形是被渲染進(jìn)屏幕空間的。使用α混合以便整個(gè)D2D//渲染目標(biāo)的背景為不可見的,且只有使用D2D繪制的東西才可見(文本)。//為D2D渲染目標(biāo)紋理對(duì)象設(shè)置混合狀態(tài)d3d11DevCon->OMSetBlendState(d2dTransparency, NULL, 0xffffffff);//Set d2d's pixel shader so lighting calculations are not done// d3d11DevCon->PSSetShader(D2D_PS, 0, 0);//設(shè)置d2d索引緩沖d3d11DevCon->IASetIndexBuffer(d2dIndexBuffer, DXGI_FORMAT_R32_UINT, 0);//設(shè)置d2d頂點(diǎn)緩沖UINT stride = sizeof(Vertex);UINT offset = 0;d3d11DevCon->IASetVertexBuffers(0, 1, &d2dVertBuffer, &stride, &offset);WVP = XMMatrixIdentity();///new // cbPerObj.World = XMMatrixTranspose(WVP);cbPerObj.WVP = XMMatrixTranspose(WVP);d3d11DevCon->UpdateSubresource(cbPerObjectBuffer, 0, NULL, &cbPerObj, 0, 0);d3d11DevCon->VSSetConstantBuffers(0, 1, &cbPerObjectBuffer);d3d11DevCon->PSSetShaderResources(0, 1, &d2dTexture);d3d11DevCon->PSSetSamplers(0, 1, &CubesTexSamplerState);d3d11DevCon->RSSetState(CWcullMode);//畫第二個(gè)立方體d3d11DevCon->DrawIndexed(6, 0, 0);}void DrawScene() {//將更新的顏色填充后緩沖 // D3DXCOLOR bgColor(red, green, blue, 1.0f);float bgColor[4] = { 0.1f, 0.1f, 0.1f, 1.0f };d3d11DevCon->ClearRenderTargetView(renderTargetView, bgColor);//刷新深度模板視圖d3d11DevCon->ClearDepthStencilView(depthStencilView, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);//newconstbuffPerFrame.light = light;d3d11DevCon->UpdateSubresource(cbPerFrameBuffer, 0, NULL, &constbuffPerFrame, 0, 0);d3d11DevCon->PSSetConstantBuffers(0, 1, &cbPerFrameBuffer);//復(fù)位頂點(diǎn)和像素著色器 // d3d11DevCon->VSSetShader(VS, 0, 0); // d3d11DevCon->PSSetShader(PS, 0, 0);//使能默認(rèn)光柵化狀態(tài) // d3d11DevCon->RSSetState(NULL);//繪制使用背面裁剪的對(duì)象//關(guān)閉背面裁剪// d3d11DevCon->RSSetState(noCull);d3d11DevCon->OMSetRenderTargets( 1, &renderTargetView, depthStencilView );d3d11DevCon->OMSetBlendState(0, 0, 0xffffffff);d3d11DevCon->VSSetShader(VS, 0, 0);d3d11DevCon->PSSetShader(PS, 0, 0);//Set the cubes index buffer//設(shè)置立方體的索引緩沖 // d3d11DevCon->IASetIndexBuffer(squareIndexBuffer, DXGI_FORMAT_R32_UINT, 0);//設(shè)置立方體的頂點(diǎn)緩沖UINT stride = sizeof(Vertex);UINT offset = 0; // d3d11DevCon->IASetVertexBuffers(0, 1, &squareVertBuffer, &stride, &offset);//設(shè)置WVP矩陣并將它送到效果文件中的常量緩沖中 // WVP = groundWorld * camView * camProjection; // cbPerObj.WVP = XMMatrixTranspose(WVP); // cbPerObj.World = XMMatrixTranspose(groundWorld); // d3d11DevCon->UpdateSubresource( cbPerObjectBuffer, 0, NULL, &cbPerObj, 0, 0 ); // d3d11DevCon->VSSetConstantBuffers( 0, 1, &cbPerObjectBuffer ); // d3d11DevCon->PSSetShaderResources( 0, 1, &CubesTexture ); // d3d11DevCon->PSSetSamplers( 0, 1, &CubesTexSamplerState ); // // d3d11DevCon->RSSetState(CCWcullMode); // d3d11DevCon->DrawIndexed( 6, 0, 0 );///**************new**************//繪制我們模型的非透明子集for(int i = 0; i < meshSubsets; ++i){//設(shè)置地面索引緩沖d3d11DevCon->IASetIndexBuffer( meshIndexBuff, DXGI_FORMAT_R32_UINT, 0);//設(shè)置地面頂點(diǎn)緩沖d3d11DevCon->IASetVertexBuffers( 0, 1, &meshVertBuff, &stride, &offset );//設(shè)置WVP矩陣并發(fā)送它到效果文件中的常量緩沖中WVP = meshWorld * camView * camProjection;cbPerObj.WVP = XMMatrixTranspose(WVP); cbPerObj.World = XMMatrixTranspose(meshWorld); cbPerObj.difColor = material[meshSubsetTexture[i]].difColor;cbPerObj.hasTexture = material[meshSubsetTexture[i]].hasTexture;///**************new**************cbPerObj.hasNormMap = material[meshSubsetTexture[i]].hasNormMap;///**************new**************d3d11DevCon->UpdateSubresource( cbPerObjectBuffer, 0, NULL, &cbPerObj, 0, 0 );d3d11DevCon->VSSetConstantBuffers( 0, 1, &cbPerObjectBuffer );d3d11DevCon->PSSetConstantBuffers( 1, 1, &cbPerObjectBuffer );if(material[meshSubsetTexture[i]].hasTexture)d3d11DevCon->PSSetShaderResources( 0, 1, &meshSRV[material[meshSubsetTexture[i]].texArrayIndex] );///**************new**************if(material[meshSubsetTexture[i]].hasNormMap)d3d11DevCon->PSSetShaderResources( 1, 1, &meshSRV[material[meshSubsetTexture[i]].normMapTexArrayIndex] );///**************new**************d3d11DevCon->PSSetSamplers( 0, 1, &CubesTexSamplerState );d3d11DevCon->RSSetState(RSCullNone);int indexStart = meshSubsetIndexStart[i];int indexDrawAmount = meshSubsetIndexStart[i+1] - meshSubsetIndexStart[i];if(!material[meshSubsetTexture[i]].transparent)d3d11DevCon->DrawIndexed( indexDrawAmount, indexStart, 0 );}///**************new**************/繪制天空的球面////設(shè)置球面的索引緩沖d3d11DevCon->IASetIndexBuffer( sphereIndexBuffer, DXGI_FORMAT_R32_UINT, 0);//設(shè)置球面的頂點(diǎn)緩沖d3d11DevCon->IASetVertexBuffers( 0, 1, &sphereVertBuffer, &stride, &offset );//設(shè)置WVP矩陣并將它發(fā)送給效果文件中的常量緩沖WVP = sphereWorld * camView * camProjection;cbPerObj.WVP = XMMatrixTranspose(WVP); cbPerObj.World = XMMatrixTranspose(sphereWorld); d3d11DevCon->UpdateSubresource( cbPerObjectBuffer, 0, NULL, &cbPerObj, 0, 0 );d3d11DevCon->VSSetConstantBuffers( 0, 1, &cbPerObjectBuffer );//發(fā)送我們的天空貼圖資源視圖到像素著色器d3d11DevCon->PSSetShaderResources( 0, 1, &smrv );d3d11DevCon->PSSetSamplers( 0, 1, &CubesTexSamplerState );//設(shè)置新的VS和PS著色器d3d11DevCon->VSSetShader(SKYMAP_VS, 0, 0);d3d11DevCon->PSSetShader(SKYMAP_PS, 0, 0);//設(shè)置新的深度模板和RS狀態(tài)d3d11DevCon->OMSetDepthStencilState(DSLessEqual, 0);d3d11DevCon->RSSetState(RSCullNone);d3d11DevCon->DrawIndexed( NumSphereFaces * 3, 0, 0 ); //設(shè)置默認(rèn)的VS,PS著色器和深度模板狀態(tài)d3d11DevCon->VSSetShader(VS, 0, 0);d3d11DevCon->PSSetShader(PS, 0, 0);d3d11DevCon->OMSetDepthStencilState(NULL, 0);///**************new************** //繪制我們的模型的透明度子集//設(shè)置我們的混合狀態(tài)d3d11DevCon->OMSetBlendState(Transparency, NULL, 0xffffffff);for(int i = 0; i < meshSubsets; ++i){//設(shè)置地面索引緩沖d3d11DevCon->IASetIndexBuffer( meshIndexBuff, DXGI_FORMAT_R32_UINT, 0);//設(shè)置地面頂點(diǎn)緩沖d3d11DevCon->IASetVertexBuffers( 0, 1, &meshVertBuff, &stride, &offset );//設(shè)置WVP矩陣并將它發(fā)送給效果文件中的常量緩沖中WVP = meshWorld * camView * camProjection;cbPerObj.WVP = XMMatrixTranspose(WVP); cbPerObj.World = XMMatrixTranspose(meshWorld); cbPerObj.difColor = material[meshSubsetTexture[i]].difColor;cbPerObj.hasTexture = material[meshSubsetTexture[i]].hasTexture;///**************new**************cbPerObj.hasNormMap = material[meshSubsetTexture[i]].hasNormMap;///**************new**************d3d11DevCon->UpdateSubresource( cbPerObjectBuffer, 0, NULL, &cbPerObj, 0, 0 );d3d11DevCon->VSSetConstantBuffers( 0, 1, &cbPerObjectBuffer );d3d11DevCon->PSSetConstantBuffers( 1, 1, &cbPerObjectBuffer );if(material[meshSubsetTexture[i]].hasTexture)d3d11DevCon->PSSetShaderResources( 0, 1, &meshSRV[material[meshSubsetTexture[i]].texArrayIndex] );///**************new**************if(material[meshSubsetTexture[i]].hasNormMap)d3d11DevCon->PSSetShaderResources( 1, 1, &meshSRV[material[meshSubsetTexture[i]].normMapTexArrayIndex] );///**************new**************d3d11DevCon->PSSetSamplers( 0, 1, &CubesTexSamplerState );d3d11DevCon->RSSetState(RSCullNone);int indexStart = meshSubsetIndexStart[i];int indexDrawAmount = meshSubsetIndexStart[i+1] - meshSubsetIndexStart[i];if(material[meshSubsetTexture[i]].transparent)d3d11DevCon->DrawIndexed( indexDrawAmount, indexStart, 0 );}///**************new************** RenderText(L"FPS: ", fps);//Present the backbuffer to the screenSwapChain->Present(0, 0); }int messageloop(){MSG msg;ZeroMemory(&msg, sizeof(MSG));//清除結(jié)構(gòu)體被設(shè)為NULL。while (true){//使用PeekMessage()檢查是否有消息傳進(jìn)來/*LPMSG lpMsg 消息結(jié)構(gòu)體的指針*HWND hWnd 發(fā)送消息的窗口句柄。若設(shè)為NULL,那么它會(huì)從當(dāng)前程序中接收來自任何一個(gè)窗口的消息*UINT wMsgFilterMin 指定消息范圍內(nèi)第一個(gè)要檢查的消息的值。若wMsgFilterMin和wMsgFilterMax都設(shè)為0,那么PeekMessage將會(huì)檢查素有的消息*UINT wMsgFilterMax 指定消息范圍內(nèi)最后一個(gè)要檢測(cè)的消息的值*UINT wRemoveMsg 指定消息的處理方式。若設(shè)置為PM_REMOVE,則在讀取之后會(huì)被刪除*/if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)){if (msg.message == WM_QUIT)break;//若消息為窗口消息,則解析并分發(fā)它。TranslateMessage()將會(huì)讓窗口做一些解析,類似鍵盤的虛擬鍵值轉(zhuǎn)換到字符形式。//而DispatchMessage()則發(fā)送消息到窗口過程WndProc。TranslateMessage(&msg);DispatchMessage(&msg);}else //若沒有窗口消息,則運(yùn)行游戲///**************new**************{frameCount++;if(GetTime() > 1.0f){fps = frameCount;frameCount = 0;StartTimer();} frameTime = GetFrameTime();///**************new**************DetectInput(frameTime);///**************new**************UpdateScene(frameTime);DrawScene();}}return msg.wParam; }//窗口消息處理函數(shù) //HWND hwnd 獲取消息的窗口句柄 //UINT msg 消息的內(nèi)容 /* *WM_ACTIVE 當(dāng)窗口激活時(shí)發(fā)送的消息 *WM_CLOSE 當(dāng)窗口關(guān)閉時(shí)發(fā)送的消息 *WM_CREATE 當(dāng)窗口創(chuàng)建時(shí)發(fā)送的消息 *WM_DESTROY 當(dāng)窗口銷毀時(shí)發(fā)送的消息 */ //wParam和lParam時(shí)消息的額外信息。使用wParam來檢測(cè)鍵盤輸入消息 LRESULT CALLBACK WndProc(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam) {// 這是事件檢測(cè)消息的地方,若escape鍵被按下,會(huì)顯示一個(gè)消息框,詢問是否真的退出。若點(diǎn)擊yes,則程序關(guān)閉。若不點(diǎn)擊,則消息框關(guān)閉。若消息包含WM_DESTROY// 則意味著窗口正在被銷毀,返回0并且程序關(guān)閉switch (msg){case WM_KEYDOWN:if (wParam == VK_ESCAPE){if (MessageBox(0, L"Are you sure you want to exit?",L"Really?", MB_YESNO | MB_ICONASTERISK) == IDYES){DestroyWindow(hwnd);}return 0;}break;case WM_DESTROY:PostQuitMessage(0);return 0;break;default:break;}//調(diào)用默認(rèn)窗口過程函數(shù)return DefWindowProc(hwnd,msg,wParam,lParam); }
效果:
參考網(wǎng)址
===》修訂20171212
總結(jié)
以上是生活随笔為你收集整理的D3D11 法线贴图(凹凸贴图)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Threejs实现天空盒,全景场景,地面
- 下一篇: 国内Android源码下载教程