• Advertisement
Sign in to follow this  

OpenGL Normal mapping? Tangents? Binormals?

This topic is 2311 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I am just starting to get into normal/bump mapping, and am curious what the "current modern method" is for doing normal mapping. I have a lot of older 3D books which make passing references to computing tangents and normals. I currently include normals in my geometry vertex format, but haven't yet seen anything that exports tangents with the geometry.


Aside from not yet knowing anything about tangents (or binormals, or bitangents, ...), I'm also using OpenGL 3.2 and trying to avoid any old deprecated methodologies. I can only assume that tangents are still needed for normal mapping (I haven't read anything to say otherwise), but is it still best to precompute them and add them to the vertex format? Or are they computed as-needed in shaders these days?

What would be a good (modern/shader) reference for learning tangents (if needed) and the basics of normal mapping?

Share this post


Link to post
Share on other sites
Advertisement
[quote name='Nairou' timestamp='1314071692' post='4852639']
I am just starting to get into normal/bump mapping, and am curious what the "current modern method" is for doing normal mapping. I have a lot of older 3D books which make passing references to computing tangents and normals. I currently include normals in my geometry vertex format, but haven't yet seen anything that exports tangents with the geometry.


Aside from not yet knowing anything about tangents (or binormals, or bitangents, ...), I'm also using OpenGL 3.2 and trying to avoid any old deprecated methodologies. I can only assume that tangents are still needed for normal mapping (I haven't read anything to say otherwise), but is it still best to precompute them and add them to the vertex format? Or are they computed as-needed in shaders these days?

What would be a good (modern/shader) reference for learning tangents (if needed) and the basics of normal mapping?

[/quote]

Tangents and binormals (/bitangents) are perpendicular vectors that run along the surface of the model that describe the direction that 2 channels of the normalmap point in, for any point on a models surface. They're exported as part of DAE and FBX formats, as well as a few others. You can caclulate them yourself, using the texturecoordinates and vertex positions each vertex per triangle, then average them out ala smooth normals. Of course, because you can do this, you can also generate them in shaders but the cost is usually fairly prohibitive.

Share this post


Link to post
Share on other sites
[quote name='Digitalfragment' timestamp='1314072270' post='4852643']
Of course, because you can do this, you can also generate them in shaders but the cost is usually fairly prohibitive.
[/quote]

Ehh, depends on the platform. A bit of extra ALU isn't going to slow down any modern GPU. :P

Share this post


Link to post
Share on other sites
[quote name='MJP' timestamp='1314076208' post='4852652']
Ehh, depends on the platform. A bit of extra ALU isn't going to slow down any modern GPU. :P
[/quote]

Haha, this is true. My judgement gets skewed because I'm used to dealing with the RSX.

Share this post


Link to post
Share on other sites
Naughty dog proposed a [url="http://jbit.net/~sparky/sfgrad_bump/mm_sfgrad_bump.pdf"]method based on derivative functions[/url] to reconstruct the perturbed normal out of the height map alone. The performance of those functions has been a bit of a pain in the past. Hopefully those are now better performing, but I'm not going to use this for a while considering I know a lot of people still running shader model 2.

Share this post


Link to post
Share on other sites
Note that using the derivative instructions to get a screen-space basis results in a severe quality reduction. It's much better to use precomputed per-vertex tangents.

Here are some comparison images. In each one, the region left of the white line uses the derivative instructions as described by the paper above. The region right of the white line uses the conventional method in which tangents are precomputed per-vertex and bitangents are generated in the vertex shader.

[img]http://www.terathon.com/external/Floor1.jpg[/img]

[img]http://www.terathon.com/external/Floor2.jpg[/img]

[img]http://www.terathon.com/external/Floor3.jpg[/img]

[img]http://www.terathon.com/external/Wall1.jpg[/img]

[img]http://www.terathon.com/external/Wall2.jpg[/img]

[img]http://www.terathon.com/external/Wall3.jpg[/img]

Share this post


Link to post
Share on other sites
[quote name='Eric Lengyel' timestamp='1314085623' post='4852688']
Note that using the derivative instructions to generate tangents and bitangents results in a severe quality reduction. It's much better to use precomputed per-vertex tangents.

Here are some comparison images. In each one, the region left of the white line uses the derivative instructions as described by the paper above. The region right of the white line uses the conventional method in which tangents are precomputed per-vertex and bitangents are generated in the vertex shader.
[/quote]

I'm sure you know this, but that paper referenced above does not generate tangents and bitangents for normal mapping...methods for doing that in the fragment shader don't produce such terrible results (especially for simple tiled cases like the ones you posted).

Share this post


Link to post
Share on other sites
You are definitely going to want to generate the tangents and bitangents, and maybe normals too yourself. Doing it in a vertex shader or geometry shader for instance will only result in per-poly normals. I suppose given a big enough patch size you could calculate accurate per vertex TBNs in a tessellation shader but it will cost you. I have a TriangleMesh class in my engine that I pump in triangles with just vertices and texcoords and from there I calculate a face normal, using that and the texcoord I calculate the face bitangents and binormals. Then you have to go through your TriangleMeshes vertices and for each one you find the surrounding triangles and average the face normals, binormals, and bitangents to get the per vertex values. It's kind of a pain but the results are a big pay off!

Share this post


Link to post
Share on other sites
Does anyone have any references on [b]why[/b] tangents and bitangents and such are used in normal mapping?

I understand that tangent space is a plane that sits on a surface perpendicular to the normal, and I see lots of documents that give the math for tangent space and calculating the tangents for a vertex. But I haven't yet found a document which explains why tangents and tangent space is important.

The best article I've found on tangents so far is [url="http://www.terathon.com/code/tangent.html"]this one[/url], but even it assumes that I already want a tangent space and want it aligned a certain way.

I'd really like to understand how normal mapping works, rather than just memorize a set of required steps.

Share this post


Link to post
Share on other sites
[quote name='Nairou' timestamp='1314150156' post='4853048']Does anyone have any references on [b]why[/b] tangents and bitangents and such are used in normal mapping?

I understand that tangent space is a plane that sits on a surface perpendicular to the normal, and I see lots of documents that give the math for tangent space and calculating the tangents for a vertex. But I haven't yet found a document which explains why tangents and tangent space is important.[/quote]The normal, tangent and binormal can be put together into a 3x3 matrix which describes 'tangent space'.

In short, normal-map data is in 'tangent space' ([i]relative to the surface orientation[/i]), but the normals we use in lighting calculations must be in a different space ([i]usually world or view space[/i]). So, we must know the orientation of the surface, so we can transform this data into the correct space ([i]i.e. relative to the world, or to the view, instead of relative to the surface[/i]).


To step back for a moment -- objects in your world are described in 'world space', where (0,0,0) describes some specific point in your world (probably the center). We say x points one way in the world ([i]maybe 'right'[/i]), z points another way ([i]maybe 'forward'[/i]), and y points up ([i]or maybe z points up for you, etc...[/i]).z = "forward" = (0,0,1)
x = "right" = (1,0,0)
y = "up" = (0,1,0)

Each object in the world's position/orientation can be described with a point ([i]which is an offset from the world's origin[/i]) and 3 directions that desribe it's rotation -- forward, right and up.
E.g. an object that is 10m above the origin, and is rotated to face the right (i.e. facing down +x, or rotated 90º around y, etc), could be described as:
pos = (0,10,0), forward = (1,0,0), right=(0,0,-1), up=(0,1,0)

We also have other 'spaces' than 'world space' though. Some things might be defined [i]relative to [/i]this object, in which case, their description would be given in that object's [i]local space[/i].
e.g. The world-space position of an object that was "2m in front of the object" would be:
relativePos = (0,0,2);
worldPos = object.position + object.right * relativePos.x + object.up * relativePos.y + object.forward * relativePos.z;
or
worldPos = (0,10,0) + (0,0,-1) * 0+ (0,1,0) * 0 + (1,0,0) * 2;


What we've just done there is actually equivalent to a matrix multiplication! If you encoded the above math into a matrix, you would have a transformation matrix which converts data from the object's [i]local space[/i], into [i]world space[/i]. I'd call this the [i]local-to-world matrix[/i].

Going back to the normal/tangent/binormal -- these are the forward/right/up directions the describe the surface of the model, relative to the object. i.e. they form a [i]surface-to-local[/i] matrix, AKA the [i]tangent space [/i][i]matrix, [/i]or [i]tangent to object transform.[/i]

The data stored in normal-maps is in [i]tangent space[/i] (i.e. relative to the surface). This matrix (i.e. these 3 directions) let us transform the texture data from being relative to the surface, to being relative to the object.
Once it's relative to the object, we can also transform it to be in world-space, or to be relative to the camera ([i]which are the spaces that lighting calculations are often done in[/i]).

Share this post


Link to post
Share on other sites
[quote name='Nairou' timestamp='1314150156' post='4853048']The best article I've found on tangents so far is [url="http://www.terathon.com/code/tangent.html"]this one[/url], but even it assumes that I already want a tangent space and want it aligned a certain way.[/quote]

I wrote that. As Hodgman describes, the tangent frame provides a matrix that allows you to transform light and view directions from object or world space into the local axis-aligned coordinate system of the normal map, or vice-versa. Basically, the tangent and bitangent at each vertex point in the directions that the x and y axes of the normal map point at those locations if you were to pull the texture off of the mesh and project it onto the tangent plane.

Btw, the term [i]binormal[/i] is still used in a lot of places, but it's not correct in the context of normal mapping. The proper term for the direction perpendicular to both the normal and tangent is the [i]bitangent[/i].

Share this post


Link to post
Share on other sites
Hodgman:
Awesome explanation! That makes sense, I think I get it now! Thank you!

Eric:
Thanks for the article! I'll have to go back and read it again now that I understand better the purpose of what is going on. :)

Share this post


Link to post
Share on other sites
FWIW - Mikkelsen posted a follow up ([url="http://mmikkelsen3d.blogspot.com/"]http://mmikkelsen3d.blogspot.com/[/url]) to that unparametrized bump mapping paper, making use of a precomputed derivative map to increase visual quality.

Share this post


Link to post
Share on other sites
[quote name='synulation' timestamp='1314213869' post='4853346']
FWIW - Mikkelsen posted a follow up ([url="http://mmikkelsen3d.blogspot.com/"]http://mmikkelsen3d.blogspot.com/[/url]) to that unparametrized bump mapping paper, making use of a precomputed derivative map to increase visual quality.
[/quote]

These public test results were produced by a member of the blender community Sean Olson

[url="http://jbit.net/~sparky/blender_deriv/compare/"]http://jbit.net/~spa..._deriv/compare/[/url]

At a moderate distance it's difficult to tell the difference between using the listing 2 method in the paper which operates off of
a height map and the method from the blog using a derivative map.
But then up close as you see in these shots you can see the difference. The derivative operator deletes one order of smoothness essentially.
This is why filtering derivatives looks smoother then taking the derivative of the filtered height signal.

However, both listing 2 and the derivative map method from the blog produce results without the aid of vertex level tangent space.
And results are good. Using derivative map vs. the height map is a trade-off between quality during texture magnification and memory budget
and imo is a call that should be made by the artist on a case by case basis.


Blender is using the method from the paper and the blog btw so you can check it out with blender though you'd have to use a build
from graphicall.org or get code from trunk to see the derivative mapping.
It's easy to drop it into your own shader anyway.
The only thing that should be mentioned which I forgot to mention in the paper is that you're supposed
to scale the bump derivatives in listing 2 (and the blog) dBs and dBt by an adjustable user-scale.

Also surf_pos and surf_norm must be in the same space ie. obj/world/view


To anyone out there who doesn't know how to generate derivative maps
there's a freely available tool here --> [url="http://jbit.net/~sparky/makedudv/"]http://jbit.net/~sparky/makedudv/[/url]
which can make them from height maps in virtually any image format.
I recommend using min. 16 bit heights and preferably float32.
Once the derivative map has been made you can compress it
into BC5 (8 bits per texel).

ZBrush can export such float32 height maps and so can blender for those looking for free options.
Mudbox and Blender both allow you to paint bump maps as well in float32
and will show you the lit result as you paint the bumps.
If anyone is feeling adventurous then there's also Cinepaint which was used
on various movie productions such as "Harry Potter and the Philosopher's Stone"
and "The Last Samurai" (and others) to paint HDR textures.

Cheers,

Morten.

Share this post


Link to post
Share on other sites
[quote name='synulation' timestamp='1314213869' post='4853346']
FWIW - Mikkelsen posted a follow up ([url="http://mmikkelsen3d.blogspot.com/"]http://mmikkelsen3d.blogspot.com/[/url]) to that unparametrized bump mapping paper, making use of a precomputed derivative map to increase visual quality.
[/quote]
I've implemented this approach using OpenGL and got on 460gtx -11% in comparison with tangent space approach


Share this post


Link to post
Share on other sites
[quote name='Digitalfragment' timestamp='1314072270' post='4852643']
Tangents and binormals (/bitangents) are perpendicular vectors....[/quote]

Is that really the case?


The space that is created is usually based on some smoothed normal and this is not perpendicular to the tangent and bitangent. I know there is some orthogonalization formula, but after all the space is not orthogonal, the tangent space matrix need to stretch and shear (in addition to just rotating like an orthogonalized matrix does). So, can someone resolve the mystery I'm stumbled into? Do I miss an important bit or is the orthogonalization mathematically wrong but somehow not visible?




while I'm hijacking this thread anyway, 2nd thing that confuses me, is it really valid to average the tangents matrices on vertices? they usually represent individual spaces for one triangle(-edge) a neighboring triangle might have a completely unrelated space which is even flipped due to UV mirroring or something. I think if the orthogonalization would remove anything but rotation, this could work if you propagate per triangle the flipping bit, but that leads to my first question.




btw. the normal perturbation gave me the same bad results Eric got, in minification I see bad aliaing (especially in specular) and with magnification you notice the linear interpolated heightmaps.

Share this post


Link to post
Share on other sites
[quote name='es' timestamp='1314795515' post='4855860']
[quote name='synulation' timestamp='1314213869' post='4853346']
FWIW - Mikkelsen posted a follow up ([url="http://mmikkelsen3d.blogspot.com/"]http://mmikkelsen3d.blogspot.com/[/url]) to that unparametrized bump mapping paper, making use of a precomputed derivative map to increase visual quality.
[/quote]
I've implemented this approach using OpenGL and got on 460gtx -11% in comparison with tangent space approach



[/quote]

Hey es,

Very interesting. Just to clarify could you
please elaborate on what you mean by 11%?
Also could you show your pixel shader? And also are you using same texture format in both cases?

Has anyone else here tried some different configurations?

Cheers,

Morten.

Share this post


Link to post
Share on other sites
[quote name='ProfL' timestamp='1314803962' post='4855914']
[quote name='Digitalfragment' timestamp='1314072270' post='4852643']
Tangents and binormals (/bitangents) are perpendicular vectors....[/quote]
Is that really the case?
[/quote]

You're right, its not really the case - it's a generalisation. We have assets here which completely break that rule. The orthonormalisation just makes it easier to conceptualise the individual channels of a normalmap, and how they relate on the surface, especially when generating normalmaps from heightmaps.

For the most part, you want the tangent space orthonormal to make the most out of the normalmap, otherwise your space ends up heavily compressed in one axis.

Share this post


Link to post
Share on other sites
[quote name='ProfL' timestamp='1314803962' post='4855914']
while I'm hijacking this thread anyway, 2nd thing that confuses me, is it really valid to average the tangents matrices on vertices? they usually represent individual spaces for one triangle(-edge) a neighboring triangle might have a completely unrelated space which is even flipped due to UV mirroring or something. I think if the orthogonalization would remove anything but rotation, this could work if you propagate per triangle the flipping bit, but that leads to my first question.
[/quote]
Seams in UV mapping, or hard edges for normal smoothing, causes split vertices. In those cases you can't average the tangents for the edge, and the tangent spaces for the neighboring triangles are not continuous.

Share this post


Link to post
Share on other sites
[quote name='Ftn' timestamp='1314968619' post='4856709']
[quote name='ProfL' timestamp='1314803962' post='4855914']
while I'm hijacking this thread anyway, 2nd thing that confuses me, is it really valid to average the tangents matrices on vertices? they usually represent individual spaces for one triangle(-edge) a neighboring triangle might have a completely unrelated space which is even flipped due to UV mirroring or something. I think if the orthogonalization would remove anything but rotation, this could work if you propagate per triangle the flipping bit, but that leads to my first question.
[/quote]
Seams in UV mapping, or hard edges for normal smoothing, causes split vertices. In those cases you can't average the tangents for the edge, and the tangent spaces for the neighboring triangles are not continuous.
[/quote]that's kind of obvious :D

I'm talking of course about shared edges/vertices. without orthogonalization you clearly don't have to average the normal, but the tangent and bitangent kinda would need that for smoothing.





@Digitalfragment thank you for confirming my worries, maybe any more takers with opinion? I wonder how you guys are dealing with those issues, obviously no game stores a full tangent matrix per vertex, all seem to run with orthogonalization mostly because the inverse in shader is just a simple transpose, not an expensive full 3x3 inverse (although it could be normalized which would at least save calculating the determinant and the division, I assume).




Share this post


Link to post
Share on other sites
[quote name='mmikkelsen' timestamp='1314879714' post='4856252']
Hey es,

Very interesting. Just to clarify could you
please elaborate on what you mean by 11%?
Also could you show your pixel shader? And also are you using same texture format in both cases?

Has anyone else here tried some different configurations?

Cheers,

Morten.
[/quote]

Hi, Morten!

I used the same BC5 textures in both cases. Here are my shaders:

Vertex Shader(derivative maps)
[source lang="cpp"]
layout(location=0) in vec3 Position;
layout(location=1) in vec2 UV;
layout(location=2) in vec3 Normal;

out block {
vec2 vUV;
vec3 vPos;
vec3 vNormal;
vec2 vScaleDuDv;
flat mat3 mNormalsWV;
} Out;

void main() {
Out.vScaleDuDv=mWorldView[gl_InstanceID][3].xy;
Out.mNormalsWV=mat3(cross(mWorldView[gl_InstanceID][1].xyz,mWorldView[gl_InstanceID][2].xyz),
cross(mWorldView[gl_InstanceID][2].xyz,mWorldView[gl_InstanceID][0].xyz),
cross(mWorldView[gl_InstanceID][0].xyz,mWorldView[gl_InstanceID][1].xyz));
Out.vUV=UV;
Out.vNormal=Normal;
Out.vPos=Position;
gl_Position=vec4((vec4(Position,1.0)*mWorldView[gl_InstanceID]).xyz,1.0)*mProjection;
}
[/source]

Fragment Shader(derivative maps)
[source lang="cpp"]
uniform sampler2D texDiffuse;
uniform sampler2D texBump;

in block {
vec2 vUV;
vec3 vPos;
vec3 vNormal;
vec2 vScaleDuDv;
flat mat3 mNormalsWV;
} In;

layout(location=0) out vec4 FragColor;

//------------------------------------------------------------------------------
// mmikkelsen3d.blogspot.com/2011/07/derivative-maps.html
//------------------------------------------------------------------------------
vec3 GetUnNormalizedBumpNormal(in vec2 dBdUV,in vec2 vUV,in vec3 vPos,in vec3 vNormal) {
// chain rule
vec2 vDxUV=dFdx(vUV);
vec2 vDyUV=dFdy(vUV);
float dBs=dot(dBdUV,vDxUV);
float dBt=dot(dBdUV,vDyUV);
vec3 vSigmaS=dFdx(vPos);
vec3 vSigmaT=dFdy(vPos);
vec3 vR1=cross(vSigmaT,vNormal);
vec3 vR2=cross(vNormal,vSigmaS);
float fDet=dot(vSigmaS,vR1);
vec3 vSurfGrad=sign(fDet)*(dBs*vR1+dBt*vR2);
return (abs(fDet)*vNormal-vSurfGrad);
}

void main() {
vec2 vDuDv=In.vScaleDuDv*(texture(texBump,In.vUV).xy*2.0-1.0);
vec3 vBumpNormal=normalize(GetUnNormalizedBumpNormal(vDuDv,In.vUV,In.vPos,normalize(In.vNormal))*In.mNormalsWV)*(gl_FrontFacing ? 1.0:-1.0);
vec4 vDiffuse=texture(texDiffuse,In.vUV);
FragColor=vec4(ToneMapFilmicU2(vSunColor*(max(dot(vSunDirection,vBumpNormal),0.0)+0.01)*vDiffuse.rgb),vDiffuse.a);
}
[/source]

Vertex Shader(tangent space)
[source lang="cpp"]
layout(location=0) in vec3 vPosition;
layout(location=1) in vec2 vUV;
layout(location=2) in vec3 vNormal;
layout(location=3) in vec4 vTangent;

out block {
vec3 vTangent;
vec3 vBiTangent;
vec3 vNormal;
vec2 vUV;
} Out;

void main() {
mat3 mNormalsWV=mat3(cross(mWorldView[gl_InstanceID][1].xyz,mWorldView[gl_InstanceID][2].xyz),
cross(mWorldView[gl_InstanceID][2].xyz,mWorldView[gl_InstanceID][0].xyz),
cross(mWorldView[gl_InstanceID][0].xyz,mWorldView[gl_InstanceID][1].xyz));
Out.vUV=vUV;
Out.vNormal=normalize(vNormal*mNormalsWV);
Out.vTangent=normalize(vTangent.xyz*mNormalsWV);
Out.vBiTangent=normalize(vTangent.w*cross(Out.vNormal,Out.vTangent));
gl_Position=vec4((vec4(vPosition,1.0)*mWorldView[gl_InstanceID]).xyz,1.0)*mProjection;
}
[/source]

Fragment Shader(tangent space)
[source lang="cpp"]
uniform sampler2D texDiffuse;
uniform sampler2D texBump;

in block {
vec3 vTangent;
vec3 vBiTangent;
vec3 vNormal;
vec2 vUV;
} In;

layout(location=0) out vec4 FragColor;

void main() {
vec3 vBump;
vBump.xy=2.0*texture(texBump,In.vUV).xy-1.0;
vBump.z=sqrt(1.0-dot(vBump.xy,vBump.xy));
vec4 vDiffuse=texture(texDiffuse,In.vUV);
vec3 vBumpNormal=normalize(normalize(In.vTangent)*vBump.x+normalize(In.vBiTangent)*vBump.y+normalize(In.vNormal)*vBump.z)*(gl_FrontFacing ? 1.0:-1.0);
FragColor=vec4(ToneMapFilmicU2(vSunColor*(max(dot(vSunDirection,vBumpNormal),0.0)+0.01)*vDiffuse.rgb),vDiffuse.a);
}
[/source]

And here are screenshots with test scene:

Sponza (derivative maps approach, 373 fps)
[url="http://imageshack.us/photo/my-images/37/testdudv.jpg/"]http://imageshack.us...7/testdudv.jpg/[/url]

Sponza (tangent space approach, 419 fps)
[url="http://imageshack.us/photo/my-images/6/testtbn.jpg/"]http://imageshack.us.../6/testtbn.jpg/[/url]

Well, 373.0 fps / 419.0 fps ~ 0.89 -> derivative maps approach is slower than tangent space approach at 11% (in my tests)

Dima.

Share this post


Link to post
Share on other sites
[quote name='ProfL' timestamp='1314974241' post='4856757']
[quote name='Ftn' timestamp='1314968619' post='4856709']
[quote name='ProfL' timestamp='1314803962' post='4855914']
while I'm hijacking this thread anyway, 2nd thing that confuses me, is it really valid to average the tangents matrices on vertices? they usually represent individual spaces for one triangle(-edge) a neighboring triangle might have a completely unrelated space which is even flipped due to UV mirroring or something. I think if the orthogonalization would remove anything but rotation, this could work if you propagate per triangle the flipping bit, but that leads to my first question.
[/quote]
Seams in UV mapping, or hard edges for normal smoothing, causes split vertices. In those cases you can't average the tangents for the edge, and the tangent spaces for the neighboring triangles are not continuous.
[/quote]that's kind of obvious :D

I'm talking of course about shared edges/vertices. without orthogonalization you clearly don't have to average the normal, but the tangent and bitangent kinda would need that for smoothing.




@Digitalfragment thank you for confirming my worries, maybe any more takers with opinion? I wonder how you guys are dealing with those issues, obviously no game stores a full tangent matrix per vertex, all seem to run with orthogonalization mostly because the inverse in shader is just a simple transpose, not an expensive full 3x3 inverse (although it could be normalized which would at least save calculating the determinant and the division, I assume).


[/quote]


Some of your questions are discussed here

--> http://wiki.blender.org/index.php/Dev:Shading/Tangent_Space_Normal_Maps

and the rest are thoroughly discussed in the thesis referenced there.
It discusses things like when to average and when to split and also which approximations
are used in games, and why, and how the baker should support these choices to avoid visual errors (not the other way around).





Share this post


Link to post
Share on other sites
[quote name='es' timestamp='1314989171' post='4856880']
Hi, Morten!


Well, 373.0 fps / 419.0 fps ~ 0.89 -> derivative maps approach is slower than tangent space approach at 11% (in my tests)

Dima.
[/quote]


Thanks a lot for sharing.

I have a few comments. One observation is that you're applying a transformation in the pixel shader
which shouldn't be there. You should simply be passing in the normal and surface position in the same space to
the interpolators such that no additional transformations are necessary.
In other words take out vScaleDuDv and mNormalsWV entirely. You're needlessly burning up
interpolators. Using fewer interpolators is supposed to be one of the advantages.

Another observation is that I neglected to mention in my paper that you need a bump scale when doing bump mapping.
So you should have a user-defined scalar constant that you scale dBs and dBt by before using them in the perturbation.
For derivative maps you can also apply this scale to dBduv if you want (the sampled derivative).

That being said even if you change this it is quite possible it'll still be a little bit slower on current gen.
However, I believe this method will be faster on coming generations of cards since it replaces interpolators with a little bit of math.

However, even if I am wrong, you have to realize what you get with this method in return. You don't need to store any tangent spaces
in memory or split any vertices. You have the option of using BC4 height maps instead of derivative maps if you're starving for memory.
Finally, it allows you to, easily, bump map synthesized surfaces such as subdiv or even surfaces being subjected to "unconventional deformations (not just skinning)" such as cloth or water (ocean/lakes) without having to recompute tangents at the vertices.

For subdiv alone this method is really extremely convenient compared to traditional normal map baking.
It's not a very good idea to bake using the control mesh as your low poly when you intend to apply it
to a subdiv surface. And it doesn't entirely make sense to use traditional tangent space generation at the vertices of the
full res subdiv surface either. And even if you did you wouldn't be able to, efficiently, generate the same spaces on the gpu.

The other thing I want to point out is your pixel shader is very short. If you compare it to a next gen shader
with possibly fancier lighting models, shadows, rims, high lights etc then the difference in perturbing a normal one way or the other
becomes very marginal relative to the full fps.

Anyway, glad you shared all your results and took the time to give it a shot.

Morten.

Share this post


Link to post
Share on other sites
[quote name='mmikkelsen' timestamp='1315056704' post='4857138']
In other words take out vScaleDuDv and mNormalsWV entirely. You're needlessly burning up
interpolators. Using fewer interpolators is supposed to be one of the advantages.

[/quote]

Morten, thanks for the tips!
I would like to say few words about my variables (but my english is not so good and perhaps i didn't understand your words properly). The vScaleDuDv is a user-scale for dBs and dBt and the mNormalsWV is a matrix which apply world-view transformations to normals. The world matrix can has scale factor and there are 2 options for computation of bumped-normal:
1. I can get bumped-normal in object space and then transform it in camera space(there is matrix multiplication in pixel shader).
2. I can get bumped-normal directly in camera space(and all matrix multiplications are made in vertex shader)

These 2 approaches give different results and i had doubts about right way of computation. In the end i chose the first approach.

Naughty Dog rules!
Uncharted rules!

Dima.

Share this post


Link to post
Share on other sites
[quote name='es' timestamp='1315084523' post='4857256']


Morten, thanks for the tips!
I would like to say few words about my variables (but my english is not so good and perhaps i didn't understand your words properly). The vScaleDuDv is a user-scale for dBs and dBt and the mNormalsWV is a matrix which apply world-view transformations to normals. The world matrix can has scale factor and there are 2 options for computation of bumped-normal:
1. I can get bumped-normal in object space and then transform it in camera space(there is matrix multiplication in pixel shader).
2. I can get bumped-normal directly in camera space(and all matrix multiplications are made in vertex shader)

These 2 approaches give different results and i had doubts about right way of computation. In the end i chose the first approach.

Naughty Dog rules!
Uncharted rules!

Dima.
[/quote]

Thanks :)

As for the shader I am still having a tough time wrapping my brain around your vScaleDuDv. It looks like you are writing the .xy
of the translation part of your world view to it? The bump scale I had in mind is a single value (1 float) specified either per material, per object or both.

As for the transformation part you are right that if your aim is to perturb in object space while doing lighting in view space then you'd be
stuck doing a transformation in your pixel shader. Furthermore, using instancing as it seems you do you'd end up
passing it to interpolators instead of the matrix being a shader constant.

I would definitely do the perturbation in view-space especially when doing instancing to avoid passing a matrix to the interpolators.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
  • Advertisement
  • Popular Now

  • Advertisement
  • Similar Content

    • By reenigne
      For those that don't know me. I am the individual who's two videos are listed here under setup for https://wiki.libsdl.org/Tutorials
      I also run grhmedia.com where I host the projects and code for the tutorials I have online.
      Recently, I received a notice from youtube they will be implementing their new policy in protecting video content as of which I won't be monetized till I meat there required number of viewers and views each month.

      Frankly, I'm pretty sick of youtube. I put up a video and someone else learns from it and puts up another video and because of the way youtube does their placement they end up with more views.
      Even guys that clearly post false information such as one individual who said GLEW 2.0 was broken because he didn't know how to compile it. He in short didn't know how to modify the script he used because he didn't understand make files and how the requirements of the compiler and library changes needed some different flags.

      At the end of the month when they implement this I will take down the content and host on my own server purely and it will be a paid system and or patreon. 

      I get my videos may be a bit dry, I generally figure people are there to learn how to do something and I rather not waste their time. 
      I used to also help people for free even those coming from the other videos. That won't be the case any more. I used to just take anyone emails and work with them my email is posted on the site.

      I don't expect to get the required number of subscribers in that time or increased views. Even if I did well it wouldn't take care of each reoccurring month.
      I figure this is simpler and I don't plan on putting some sort of exorbitant fee for a monthly subscription or the like.
      I was thinking on the lines of a few dollars 1,2, and 3 and the larger subscription gets you assistance with the content in the tutorials if needed that month.
      Maybe another fee if it is related but not directly in the content. 
      The fees would serve to cut down on the number of people who ask for help and maybe encourage some of the people to actually pay attention to what is said rather than do their own thing. That actually turns out to be 90% of the issues. I spent 6 hours helping one individual last week I must have asked him 20 times did you do exactly like I said in the video even pointed directly to the section. When he finally sent me a copy of the what he entered I knew then and there he had not. I circled it and I pointed out that wasn't what I said to do in the video. I didn't tell him what was wrong and how I knew that way he would go back and actually follow what it said to do. He then reported it worked. Yea, no kidding following directions works. But hey isn't alone and well its part of the learning process.

      So the point of this isn't to be a gripe session. I'm just looking for a bit of feed back. Do you think the fees are unreasonable?
      Should I keep the youtube channel and do just the fees with patreon or do you think locking the content to my site and require a subscription is an idea.

      I'm just looking at the fact it is unrealistic to think youtube/google will actually get stuff right or that youtube viewers will actually bother to start looking for more accurate videos. 
    • By Balma Alparisi
      i got error 1282 in my code.
      sf::ContextSettings settings; settings.majorVersion = 4; settings.minorVersion = 5; settings.attributeFlags = settings.Core; sf::Window window; window.create(sf::VideoMode(1600, 900), "Texture Unit Rectangle", sf::Style::Close, settings); window.setActive(true); window.setVerticalSyncEnabled(true); glewInit(); GLuint shaderProgram = createShaderProgram("FX/Rectangle.vss", "FX/Rectangle.fss"); float vertex[] = { -0.5f,0.5f,0.0f, 0.0f,0.0f, -0.5f,-0.5f,0.0f, 0.0f,1.0f, 0.5f,0.5f,0.0f, 1.0f,0.0f, 0.5,-0.5f,0.0f, 1.0f,1.0f, }; GLuint indices[] = { 0,1,2, 1,2,3, }; GLuint vao; glGenVertexArrays(1, &vao); glBindVertexArray(vao); GLuint vbo; glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(vertex), vertex, GL_STATIC_DRAW); GLuint ebo; glGenBuffers(1, &ebo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices,GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, false, sizeof(float) * 5, (void*)0); glEnableVertexAttribArray(0); glVertexAttribPointer(1, 2, GL_FLOAT, false, sizeof(float) * 5, (void*)(sizeof(float) * 3)); glEnableVertexAttribArray(1); GLuint texture[2]; glGenTextures(2, texture); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture[0]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); sf::Image* imageOne = new sf::Image; bool isImageOneLoaded = imageOne->loadFromFile("Texture/container.jpg"); if (isImageOneLoaded) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, imageOne->getSize().x, imageOne->getSize().y, 0, GL_RGBA, GL_UNSIGNED_BYTE, imageOne->getPixelsPtr()); glGenerateMipmap(GL_TEXTURE_2D); } delete imageOne; glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, texture[1]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); sf::Image* imageTwo = new sf::Image; bool isImageTwoLoaded = imageTwo->loadFromFile("Texture/awesomeface.png"); if (isImageTwoLoaded) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, imageTwo->getSize().x, imageTwo->getSize().y, 0, GL_RGBA, GL_UNSIGNED_BYTE, imageTwo->getPixelsPtr()); glGenerateMipmap(GL_TEXTURE_2D); } delete imageTwo; glUniform1i(glGetUniformLocation(shaderProgram, "inTextureOne"), 0); glUniform1i(glGetUniformLocation(shaderProgram, "inTextureTwo"), 1); GLenum error = glGetError(); std::cout << error << std::endl; sf::Event event; bool isRunning = true; while (isRunning) { while (window.pollEvent(event)) { if (event.type == event.Closed) { isRunning = false; } } glClear(GL_COLOR_BUFFER_BIT); if (isImageOneLoaded && isImageTwoLoaded) { glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture[0]); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, texture[1]); glUseProgram(shaderProgram); } glBindVertexArray(vao); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, nullptr); glBindVertexArray(0); window.display(); } glDeleteVertexArrays(1, &vao); glDeleteBuffers(1, &vbo); glDeleteBuffers(1, &ebo); glDeleteProgram(shaderProgram); glDeleteTextures(2,texture); return 0; } and this is the vertex shader
      #version 450 core layout(location=0) in vec3 inPos; layout(location=1) in vec2 inTexCoord; out vec2 TexCoord; void main() { gl_Position=vec4(inPos,1.0); TexCoord=inTexCoord; } and the fragment shader
      #version 450 core in vec2 TexCoord; uniform sampler2D inTextureOne; uniform sampler2D inTextureTwo; out vec4 FragmentColor; void main() { FragmentColor=mix(texture(inTextureOne,TexCoord),texture(inTextureTwo,TexCoord),0.2); } I was expecting awesomeface.png on top of container.jpg

    • By khawk
      We've just released all of the source code for the NeHe OpenGL lessons on our Github page at https://github.com/gamedev-net/nehe-opengl. code - 43 total platforms, configurations, and languages are included.
      Now operated by GameDev.net, NeHe is located at http://nehe.gamedev.net where it has been a valuable resource for developers wanting to learn OpenGL and graphics programming.

      View full story
    • By TheChubu
      The Khronos™ Group, an open consortium of leading hardware and software companies, announces from the SIGGRAPH 2017 Conference the immediate public availability of the OpenGL® 4.6 specification. OpenGL 4.6 integrates the functionality of numerous ARB and EXT extensions created by Khronos members AMD, Intel, and NVIDIA into core, including the capability to ingest SPIR-V™ shaders.
      SPIR-V is a Khronos-defined standard intermediate language for parallel compute and graphics, which enables content creators to simplify their shader authoring and management pipelines while providing significant source shading language flexibility. OpenGL 4.6 adds support for ingesting SPIR-V shaders to the core specification, guaranteeing that SPIR-V shaders will be widely supported by OpenGL implementations.
      OpenGL 4.6 adds the functionality of these ARB extensions to OpenGL’s core specification:
      GL_ARB_gl_spirv and GL_ARB_spirv_extensions to standardize SPIR-V support for OpenGL GL_ARB_indirect_parameters and GL_ARB_shader_draw_parameters for reducing the CPU overhead associated with rendering batches of geometry GL_ARB_pipeline_statistics_query and GL_ARB_transform_feedback_overflow_querystandardize OpenGL support for features available in Direct3D GL_ARB_texture_filter_anisotropic (based on GL_EXT_texture_filter_anisotropic) brings previously IP encumbered functionality into OpenGL to improve the visual quality of textured scenes GL_ARB_polygon_offset_clamp (based on GL_EXT_polygon_offset_clamp) suppresses a common visual artifact known as a “light leak” associated with rendering shadows GL_ARB_shader_atomic_counter_ops and GL_ARB_shader_group_vote add shader intrinsics supported by all desktop vendors to improve functionality and performance GL_KHR_no_error reduces driver overhead by allowing the application to indicate that it expects error-free operation so errors need not be generated In addition to the above features being added to OpenGL 4.6, the following are being released as extensions:
      GL_KHR_parallel_shader_compile allows applications to launch multiple shader compile threads to improve shader compile throughput WGL_ARB_create_context_no_error and GXL_ARB_create_context_no_error allow no error contexts to be created with WGL or GLX that support the GL_KHR_no_error extension “I’m proud to announce OpenGL 4.6 as the most feature-rich version of OpenGL yet. We've brought together the most popular, widely-supported extensions into a new core specification to give OpenGL developers and end users an improved baseline feature set. This includes resolving previous intellectual property roadblocks to bringing anisotropic texture filtering and polygon offset clamping into the core specification to enable widespread implementation and usage,” said Piers Daniell, chair of the OpenGL Working Group at Khronos. “The OpenGL working group will continue to respond to market needs and work with GPU vendors to ensure OpenGL remains a viable and evolving graphics API for all its customers and users across many vital industries.“
      The OpenGL 4.6 specification can be found at https://khronos.org/registry/OpenGL/index_gl.php. The GLSL to SPIR-V compiler glslang has been updated with GLSL 4.60 support, and can be found at https://github.com/KhronosGroup/glslang.
      Sophisticated graphics applications will also benefit from a set of newly released extensions for both OpenGL and OpenGL ES to enable interoperability with Vulkan and Direct3D. These extensions are named:
      GL_EXT_memory_object GL_EXT_memory_object_fd GL_EXT_memory_object_win32 GL_EXT_semaphore GL_EXT_semaphore_fd GL_EXT_semaphore_win32 GL_EXT_win32_keyed_mutex They can be found at: https://khronos.org/registry/OpenGL/index_gl.php
      Industry Support for OpenGL 4.6
      “With OpenGL 4.6 our customers have an improved set of core features available on our full range of OpenGL 4.x capable GPUs. These features provide improved rendering quality, performance and functionality. As the graphics industry’s most popular API, we fully support OpenGL and will continue to work closely with the Khronos Group on the development of new OpenGL specifications and extensions for our customers. NVIDIA has released beta OpenGL 4.6 drivers today at https://developer.nvidia.com/opengl-driver so developers can use these new features right away,” said Bob Pette, vice president, Professional Graphics at NVIDIA.
      "OpenGL 4.6 will be the first OpenGL release where conformant open source implementations based on the Mesa project will be deliverable in a reasonable timeframe after release. The open sourcing of the OpenGL conformance test suite and ongoing work between Khronos and X.org will also allow for non-vendor led open source implementations to achieve conformance in the near future," said David Airlie, senior principal engineer at Red Hat, and developer on Mesa/X.org projects.

      View full story
    • By _OskaR
      Hi,
      I have an OpenGL application but without possibility to wite own shaders.
      I need to perform small VS modification - is possible to do it in an alternative way? Do we have apps or driver modifictions which will catch the shader sent to GPU and override it?
  • Advertisement