Problem
Although a plane object with a constant normal works well in the previous tutorial, it will still be difficult to map a surface or a surface with a corner.
The main problem is that the deviation from the normal contained in the concave-convex ing is in the tangent space, which means it is associated with the default normal.
To visualize this problem, imagine creating a cylinder, as shown in 5-30. The left graph shows the default normal of the cylindrical vertex.
Figure 5-30 default normal and concave-convex ing normal of the cylinder
Imagine you want to use the concave-convex ing for this cylinder. For example, you want to use a concave/convex ing that contains (-, 1) direction normal to all pixels of the cylinder. This Normal deflection is 45 degrees left relative to the default normal.
The correct way to obtain this normal is to rotate 45 degrees left along the default normal at the starting point of the default normal. Let's take a look at the vertex normal 0, 4, and 6. The direction of each pixel in the cylinder is different, because this direction depends on the default normal of the pixel! If this is done for each normal, you will eventually get the result shown in the right figure. These Normal directions all deviate 45 degrees from the original normal to the left.
However, if you want to use this normal to calculate the light, you need to find the normal (-, 1) corresponding to the direction of the world space. This is required, because you need to use two vectors for illumination calculation, and these two vectors must be defined in the same space. You wantProgramSpecifies the direction of the light in the world space.
Solution
The three color channels in the normal ing contain the normal line coordinates in the tangent space. That is, the coordinates represent the deviation of the default normal compared to the default normal. The local coordinate system of each pixel is different, because it depends on the default normal, and the default normal direction on a surface is different. This local coordinate system is called the tangent space.
TIPS:To understand the tangent space, you can imagine standing on the pixel of the cylinder shown in 5-30 and following the normal direction. Now you can use the top (along the default normal direction) as the Z axis, and the right side is the X axis, and the front is the Y axis.
Three gray arrows in the "A" figure in the tangent Coordinate System 5-31. Note that the default normal of the pixel is the Z axis in the tangent space (see the previous Tips ). The X and Y axes of the tangent space must be perpendicular to the Z axis. The Z axis is perpendicular to the object (because this is the default normal direction). The X axis and Y axis are tangent to the object and correspond to the tangent and subnormal respectively.
The three color channels sampled from the concave and convex textures contain the normal data defined in the tangent space. It is represented by the black arrow in the figure, and the corresponding offset is X = 0.3, y = 0 and Z = 0.8. In "A", you see a new line biased towards the X axis.
Finally, we need to calculate the pixel glow, which requires getting the normal defined in the tangent space and the point multiplication defined in the light direction in the world space. To calculate the point multiplication of two vectors, the two vectors must be in the same space. So you can either convert the light direction from the world space to the tangent space, or convert the normal line from the tangent space to the world space. In this tutorial, we first use the second method. The first method is used in the last section of the tutorial.
Figure 5-31 deviation from normal in the tangent space (A), model space (B), and World Space (c)
Working Principle
For each pixel, You need to sample the concave-convex texture to obtain the deviation from the normal line relative to the tangent space. Finally, we need to know the coordinates of this normal in the world space before we can perform point multiplication with the ray method.
Conversion from tangent space to World Space
The normal sample from the concave-convex map is defined in the tangent space. For example, a circular tower is cylindrical, as shown in Figure 5-31. The deviation from the normal of each pixel needs to be first converted to the model space, that is, the coordinate space of the tower. This will get the default normal in the model space.
TIPS:To understand the coordinate space of the tower, imagine the initial position of your standing in the tower, such as the central position inside the tower. Now, you have the Y axis above, the right side is the X axis, and the rear is the Z axis. The deviation from the normal is specified by the coordinate system of the tower.
This transformation is represented by the arrow from "A" to "B" in Figure 5-31. In "A", the legal coordinate in the tangent space is (0.3, 0, 0.8), while in "B", the legal coordinate in the model space is (0.2, 0, 0.85) (determined by the coordinates of the two systems ).
You can use a matrix containing the rotated world to draw a tower (for example, to draw a Leaning Tower of Pisa ). In this example, you need to remove the rotation of the obtained normal to obtain the absolute (World) Direction of the normal. This transformation is represented by the arrow pointing from "B" to "C" in Figure 5-31 (note that the model coordinates in this graph are actually the rotation of the world coordinates ). Finally, you get the normal in the world coordinates.
Custom vertex format
To convert the normal line from the tangent space to the model space, multiply it by the correct transformation matrix. You need to perform this operation on each pixel. To create this matrix, you must first know the X, Y, and Z axes (normal, tangent, and subnormal) of each vertex in the tangent space ).
The default normal is different from the Z axis, and the X and Y axes must be perpendicular to the Z axis. Therefore, the three axes of each vertex are usually different. Because the three axes are orthogonal, you only need to know any two of them, and you can get the third axis by multiplying them. One axis (z) is the default normal. You can useCodeGet, the tangent vector is provided by the model, or defined by itself in simple cases (such as a cylinder.
Note:In this example, vertex shader calculates the subnormal vector through the cross multiplication line and the tangent vector. In this case, the vertex only needs to store the regular line and the tangent vector. You can also compile a custom model processor to calculate the subnormal of each vertex and store it in the vertex. You only need to use meshhelper. calculatetangentframes to help you complete this heavy work. The advantage of this is that the video card does not need to calculate the subnormal vector at each frame.
First, you need to define a custom vertex format to store the 3d positions, texture coordinates, normal and tangent of each vertex. See tutorial 5-14 to obtain the details of the custom vertex format.
Public struct detail {public vector3 position; Public vector2 texcoords; Public vector3 normal; Public vector3 tangent; Public reverse (vector3 position, vector2 texcoords, vector3 normal, vector3 tangent) {This. position = position; this. texcoords = texcoords; this. normal = normal; this. tangent = tangent;} public static readonly vertexelement [] vertexelements = {New vertexelement (0, 0, vertexelementformat. vector3, vertexelementmethod. default, vertexelementusage. position, 0), new vertexelement (0, sizeof (float) * 3, vertexelementformat. vector2, vertexelementmethod. default, vertexelementusage. texturecoordinate, 0), new vertexelement (0, sizeof (float) * (3 + 2), vertexelementformat. vector3, vertexelementmethod. default, vertexelementusage. normal, 0), new vertexelement (0, sizeof (float) * (3 + 2 + 3), vertexelementformat. vector3, vertexelementmethod. default, vertexelementusage. tangent, 0),}; public static readonly int sizeinbytes = sizeof (float) * (3 + 2 + 3 + 3 );}
Each vertex needs to store a vector3 representing the position, a vector2 representing the texture coordinate, two vector3 representing the line and tangent, a total of 11 floating point numbers, and the subnormal is calculated in vertex shader.
Define the normal and tangent of each vertex
In this example, you define some triangles to create a tower (a cylindrical wall), and use the Code 5-7 to generate normal data.
As mentioned above, the tangent direction is perpendicular to the normal and is tangent to the tower. In this example, you define a vertical tower, so you know that the upward direction does not overlap the tower and perpendicular to all the normal directions of the tower. This is the tangent direction.
The following code defines a cylindrical shape. Calculate the 3D position for each generated vertex, And take (0, 1, 0) upward direction as the tangent direction.
private void initvertices () {list
verticeslist = new list
(); int detail = 20; float radius = 2; float Height = 8; for (INT I = 0; I
Next, generate an index based on the vertex. All the code has been explained in tutorial 5-7:
Vertices = initvertices (); indices = initindices (vertices); vertices = generatenormalsfortrianglelist (vertices, indices );
After the vertex and index are set, the. FX file can be processed below.
XNa-to-HLSL variable
All 3dhaders must pass the world, view, and projection matrices. It does not work because there is no light concave-convex ing, so you need to set the light direction. Finally, the xtexstretch variable allows you to define the number of tile times of the brick texture.
You need a color texture sampling color and a concave/convex texture that includes the normal information defined in the tangent space.
Vertex shader always converts the 3D position of each vertex to the 2D screen coordinate, and transmits the texture coordinate. To convert pixel shader from the tangent space to the world space, vertex shader must calculate the tangent-to-world matrix and pass it to pixel shader.
Float4x4 xworld; float4x4 xview; float4x4 xprojection; float3 xlightdirection; float inline; texture xtexture; sampler inline = inline {texture = <xtexture>; magfilter = Linear; minfilter = Linear; mipfilter = Linear; addressu = wrap; addressv = wrap;}; texture xbumpmap; sampler vertex = sampler_state {texture = <xbumpmap>; magfilter = Linear; minfilter = Linear; mipfilter = Linear; addressu = wrap; addressv = wrap;}; struct comment {float4 position: position; float2 texcoord: comment; float3x3 ttw: texcoord1;}; struct BMP ixeltoframe {float4 color: color0 ;}
Note:This Code uses the semantic texcoord1 to pass a 3 × 3 matrix. This will be compiled, but the background uses texcoor2 and texcoord3, so you can no longer use them.
Vertex shader
Vertex shader converts 3d positions to 2D screen coordinates and transmits texture coordinates to pixel shader:
Bmvertextopixel bmvertexshader (float4 inpos: position0, float3 innormal: normal0, float2 intexcoord: Unknown, float3 intangent: tangent0) {export output = (Inline) 0; float4x4 previewprojection = MUL (xview, xprojection); float4x4 preworldviewprojection = MUL (xworld, previewprojection); output. position = MUL (inpos, preworldviewprojection); output. texcoord = intexcoord; return output ;}
Next, you need to add some code to the vertex shader to calculate the tangent-to-world matrix. As mentioned above, this conversion involves two processes. First, convert the coordinates of the normal from the tangent space to the model space and then to the world space.
First, define a tangenttoobject matrix. to define this matrix, you need to know the basic vector of the coordinate axis-the normal, tangent, and subnormal of the tangent space.
Vertex shader accepts the normal and tangent of each vertex. As mentioned above, you can calculate the subnormal through the cross multiplication, because the subnormal vector is orthogonal to the normal and the tangent.
Float3 binormal = normalize (Cross (intangent, innormal ));
After the subnormal is calculated, the tangent-to-object matrix can be constructed, because the three rows of this matrix represent the three vectors, which need to be normalized:
Float3x3 tangenttoobject; tangenttoobject [0] = normalize (binormal); tangenttoobject [1] = normalize (intangent); tangenttoobject [2] = normalize (innormal );
TIPS:After each row of the normalization matrix, because these three vectors are orthogonal, the inverse matrix of this matrix is equal to its transpose matrix, you can perform an image on the elements in the upper left corner to the lower right corner of the Matrix to obtain its transpose matrix. This makes it easier to calculate the inverse matrix.
All you need to do is to combine the tangent-to-object matrix and the object-to-world matrix by multiplying them. The object-to-world matrix is usually the world matrix (for example, the rotation of the Inclusion Tower), so the final code is:
Float3x3 tangenttoworld = MUL (tangenttoobject, xworld); output. ttw = tangenttoworld;
Pass this matrix to pixel shader. Now pixel shader can easily convert a vector from the tangent space to the world matrix by multiplying the vector by this matrix!
Pixel shader
After completing all the preparations in vertex shader, pixel shader looks very simple:
Bmvertextopixel pSIN: color0 {BMP eltoframe output = (BMP eltoframe) 0; float3 bumpcolor = tex2d (bumpmapsampler, pSIN. texcoord * xtexstretch); float3 normalt = (bumpcolor-0.5f) * 2.0f; float3 normalw = MUL (normalt, pSIN. ttw); float lightfactor = dot (-Normalize (normalw), normalize (xlightdirection); float4 texcolor = tex2d (texturesampler, pSIN. texcoord * xtexstretch); output. color = lightfactor * texcolor; return output ;}
First, sample the concave-convex ing. The color contains the coordinates of the three color channels corresponding to the deviation from the normal in the tangent space.
As mentioned in the "pixel shader" section in the previous tutorial, the color channel ranges from 0 to 1, while the linear coordinates range from-1 to 1. Therefore, first map the value minus 0.5 to the [-0.5, 0.5] interval and then multiply by 2 to the [-] interval. The calculation results are stored in the normalt variable. The normalt variable contains data that defines the deviation from the normal in the tangent space.
The value of normalt is (0, 0, 1), indicating that the deviation from the normal is equal to the default normal (that is, the Z axis direction in the tangent space ). The normalt value is (0, 0.7, 0.7) the 45-degree angle direction between the default normal and the tangent (the y-axis direction of the tangent space.
Multiply the normalt by the tangent-to-world matrix to convert the tangent space to the World Space and obtain the normalw value, which is the normal of the world space.
Note:You can immediately convert the normal from the tangent space to the world space, because the tangent-to-world matrix is a combination of the tangent-to-object matrix and the object-to-world matrix.
Finally, when you know the normal in the world space, you can multiply this vector by the light vector. As explained in tutorial 6-1, this point multiplication gives the light intensity, multiply the intensity by the color. Because the normal of each pixel is different, the degree of reflection of each pixel is also different.
Code HLSL
The shader must calculate the tangent-to-world matrix and pass it to the pixel shader:
Bmvertextopixel bmvertexshader (float4 inpos: position0, float3 innormal: normal0, float2 intexcoord: Unknown, float3 intangent: tangent0) {export output = (Inline) 0; float4x4 previewprojection = MUL (xview, xprojection); float4x4 preworldviewprojection = MUL (xworld, previewprojection); output. position = MUL (inpos, preworldviewprojection); output. texcoord = intexcoord; float3 binormal = cross (intangent, innormal); float3x3 tangenttoobject; bytes [0] = normalize (binormal); tangenttoobject [1] = normalize (intangent ); tangenttoobject [2] = normalize (innormal); float3x3 tangenttoworld = MUL (tangenttoobject, xworld); output. ttw = tangenttoworld; return output ;}
Pixel shader samples the concave-convex texture and maps the color to the [-] range to obtain the normal line of the tangent space. Then, multiply the tangent-to-world matrix to obtain the normal line in the world space, then, take the light direction:
Bmvertextopixel pSIN: color0 {BMP eltoframe output = (BMP eltoframe) 0; float3 bumpcolor = tex2d (bumpmapsampler, pSIN. texcoord * xtexstretch); float3 normalt = (bumpcolor-0.5f) * 2.0f; float3 normalw = MUL (normalt, pSIN. ttw); float lightfactor = dot (-Normalize (normalw), normalize (xlightdirection); float4 texcolor = tex2d (texturesampler, pSIN. texcoord * xtexstretch); output. color = lightfactor * texcolor; return output ;}
XNa Section
The xNa project provides the tangent of each vertex. The tangent vector is perpendicular to the normal. The method for generating these vertices has been written before.
Finally, set the effect parameter and draw a triangle. The Code is as follows:
Effect. currenttechnique = effect. techniques ["bumpmapping"]; effect. parameters ["xworld"]. setvalue (matrix. identity); effect. parameters ["xview"]. setvalue (fpscam. viewmatrix); effect. parameters ["xprojection"]. setvalue (fpscam. projectionmatrix); effect. parameters ["xtexture"]. setvalue (mytexture); effect. parameters ["xbumpmap"]. setvalue (mybumpmap); effect. parameters ["xlightdirection"]. setvalue (lightdirection); effect. parameters ["xtexstretch"]. setvalue (4.0f); effect. begin (); foreach (effectpass pass in effect. currenttechnique. passes) {pass. begin (); device. vertexdeclaration = myvertexdeclaration; device. drawuserindexedprimitives <vertpostexnormtan> (primitivetype. trianglelist, vertices, 0, vertices. length, indices, 0, indices. length/3); pass. end ();} effect. end ();
Opposite Method
The previous code shows how to build the tangenttoworld matrix, so that each pixel can convert its normal from the tangent space to the world space. This step needs to be completed before multiplying the light direction point, because the light direction is in the world space.
You can also use another method: You can convert the direction of light from the world space to the tangent space and point it to the normal in the tangent space. This is interesting because the light direction of each pixel is the same, so we can convert the light direction in vertex shader and pass it to pixel shader. In this way, pixel shader can perform vertex multiplication calculation immediately without any conversion!
Note:With this method, each triangle only needs to undergo three light vector transformations, instead of converting the normal of each pixel of the triangle.
You pass the light vector converted to the tangent space to the pixel shader instead of the tangenttoworld matrix:
Struct bmvertextopixel {float4 position: position; float2 texcoord: texcoord0; float3 lightdirt: texcoord1 ;};
In vertex shader, you have calculated the tangenttoworld matrix. This time, you want to convert the ray vector from the world space to the tangent space, so you need to require the inverse matrix of the tangenttoworld matrix.
Calculation of the inverse matrix is a complex operation. Fortunately, the tangenttoworld matrix is composed of three orthogonal, normalized (subnormal, tangent, and normal) vectors. Generally, you use a vector as the first parameter in the multiplication operation, and a matrix as the second matrix:
Float3 vectorw = MUL (vectort, tangenttoworld );
In special cases of the three orthogonal normalized vectors, you can obtain the inverse matrix to convert a vector by changing the multiplication order:
Float3 vectort = MUL (tangenttoworld, vectorw );
Note:This is because the inverse matrix of a matrix composed of three orthogonal and normalized vectors is equal to its transpose matrix.
This is exactly the result you want to get: converting the ray vector from the world space to the tangent space:
Output. lightdirt = MUL (tangenttoworld, xlightdirection );
After calculating the light direction of the tangent space, pass it to pixel shader. Because the normal and light direction sampled from the ing are in the tangent space, you can directly multiply the two points:
Float3 bumpcolor = tex2d (bumpmapsampler, pSIN. texcoord * xtexstretch); float3 normalt = (bumpcolor-0.5f) * 2.0f; float lightfactor = dot (-Normalize (normalt), normalize (pSIN. lightdirt ));