Sign in to follow this  
Migi0027

DX11 DX11 Shader Generation

Recommended Posts

Migi0027    4628

This is just a question of curiosity by the way. wink.png

 

So some few weeks ago I was curious on how to render an object multiple times with different to archive different results, and the only problem is that if I try to use additive blending, I get a black object.  Now to the point,  because of this, a guy said to me:

 

"You could also just write a single shader that performs the appropriate computations for the diffuse term, direction lighting term, and reads the color from the read and modulates it by the lighting terms."

 

Now this is a good idea, but i wanted to give my engine the freedom to render any shaders together (render 1, render 2, etc...), and by that it would be easier! But he is right...

 

So I though, why not generate a shader, like:

String Diff  = "color = somecolor"
String Light = "...color += something..."

PixelShader += Diff;
PixelShader += Light;

WholeShader = Buffers + Layout + Vertex + Pixel;

Compile WholeShader

Now could something like this be made, due to flexibility, and is this how real material editors work? (E.g. UDK Material Editor)

 

Thank You

Share this post


Link to post
Share on other sites
MJP    19753

Yes, that is the basic idea behind node-based shader editors like the one in UDK. Once you start implementing it though I think you'll find that it can get pretty hairy, due to complex interactions between the various features that you support. Personally I think it's easier (and better overall) to go with an ubershader approach where you just turn features on and off.

Share this post


Link to post
Share on other sites
Migi0027    4628

Yes, that is the basic idea behind node-based shader editors like the one in UDK. Once you start implementing it though I think you'll find that it can get pretty hairy, due to complex interactions between the various features that you support. Personally I think it's easier (and better overall) to go with an ubershader approach where you just turn features on and off.

 

How exacly does this ubershader work(I've heard of it, but never wen't into it)? Is it a framework?

Share this post


Link to post
Share on other sites
MJP    19753

"Ubershader" is just a name for a general pattern for authoring shader permutations. Typically you will write one large vertex and pixel shader with all possible features implemented, and then you will wrap the corresponding code for a certain features in "#ifdef" preprocessor statements. This allows you to compile different permutations of your shader with various features enabled or disabled by passing different macro definitions when compiling the shader. Here's a really simple example:

 

 

#ifdef ENABLE_COLOR_TEXTURE
Texture2D ColorTexture;
SamplerSTate ColorTextureSampler;
#endif

struct PSInput
{
    float4 VertexColor : VTXCOLOR;

#ifdef ENABLE_COLOR_TEXTURE
    float2 UV          : UV0;
#endif
};

float4 PSMain(in PSInput input) : SV_Target0
{
    float4 color = input.VertexColor;

#ifdef ENABLE_COLOR_TEXTURE
    color *= ColorTexture.Sample(ColorTextureSampler, input.UV);
#endif

    return color;
}


This is pixel shader for an ubershader that has 2 permutations: one with a color texture enabled, and one without. So you would compile one where you'd specify that you want ENABLE_COLOR_TEXTURE defined as an extra preprocessor macro, and one where you wouldn't. Then you can switch between the two at runtime depending on what you need for a particular mesh. Or alternatively you can have your features be options when authoring a material, and then you can specifically compile a shader permutation for that material. Typically you'll have lots of options that you want to disable, such as lighting, normal mapping, skinning, etc. Supporting all possible permutations of a bunch of on/off options then requires you to compile 2^N shaders, where N is the number of options you want to support. A common way index into all of these shaders is with a bitfield, where each the value of each bit corresponds to a feature being turned on or off. This gives you a simple hash that you can use to lookup into std::map or a similar data structure.

You can also support enabling or disabling features by wrapping them in regular if statements, and passing a bool through a constant buffer to specify whether you want them on or off. This saves you from having to compile different shaders and switch between them at runtime, which can save you build time and can also potentially save you some CPU time due to driver overhead from switching shaders. However in generally it will result in less optimal compiled shader code, since the compiler will be unable to fully optimize out the code in a branch that's not taken (or any code that produces results required for the branch not taken). This can result in extra instructions being executed, and potentially higher register usage which reduces thread occupancy. There's also some cost to actually executing a branch instruction, although this is generally small on modern DX11-capable hardware. The one major limitation of branches is that you can't use them to disable vertex shader inputs. Here's a simple example showing what I mean:

 

cbuffer VSConstants
{
    float4x4 World;
    float4x4 WorldViewProj;
}

#ifdef ENABLE_SKINNING
static const uint MaxBones = 256;

cbuffer SkinningConstants
{
    float4x4 Bones[MaxBones];
}

struct VSInput
{
    float3 Position : POSITION;
    float3 Normal : NORMAL;

#ifdef ENABLE_SKINNING
    uint4 SkinIndices : SKININDICES;
    float4 SkinWeights : SKINWEIGHTS;
#endif
};

struct VSOutput
{
    float4 Position : SV_Position;
    float3 Normal : NORMAL;
};

VSOutput VSMain(in VSInput input)
{
    VSOutput output;

#ifdef ENABLE_SKINNING
    float3 position = 0.0f;
    float3 normal = 0.0f;

    [unroll]
    for(uint i = 0; i < 4; ++i)
    {
        float4x4 bone = Bones[input.SkinIndices[i]];
        float weight = input.SkinWeights[i];
        position += mul(float4(input.Position, 1.0f), bone).xyz * weight;
        normal = mul(float4(normal, 0.0f), bone).xyz * weight;
    }
#else
    float3 position = input.Position;
    float3 normal = input.Normal;
#endif

    output.Position = mul(float4(position, 1.0f), WorldViewProj).xyz;
    output.Normal = mul(float4(normal, 0.0f), World).xyz;

    return output;
}


If you were to try to implement this feature using runtime branching instead of preprocessor macros, you'd have the problem that you wouldn't be able to disable the SkinWeights and SkinIndices vertex inputs. This means that even when skinning is disabled the shader would still expect those elements to be provided in a vertex buffer, so you'd either need to pad out your vertex buffers or pass dummy vertex buffers as a separate stream. It also means that the shader will expect the "Bones" constant buffer to be bound, which means you'll get spammed with warnings from the debug device (although the shader will still work fine as long as you don't actually use anything from that constant buffer). Edited by MJP

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

  • Similar Content

    • By isu diss
       I'm trying to code Rayleigh part of Nishita's model (Display Method of the Sky Color Taking into Account Multiple Scattering). I get black screen no colors. Can anyone find the issue for me?
       
      #define InnerRadius 6320000 #define OutterRadius 6420000 #define PI 3.141592653 #define Isteps 20 #define Ksteps 10 static float3 RayleighCoeffs = float3(6.55e-6, 1.73e-5, 2.30e-5); RWTexture2D<float4> SkyColors : register (u0); cbuffer CSCONSTANTBUF : register( b0 ) { float fHeight; float3 vSunDir; } float Density(float Height) { return exp(-Height/8340); } float RaySphereIntersection(float3 RayOrigin, float3 RayDirection, float3 SphereOrigin, float Radius) { float t1, t0; float3 L = SphereOrigin - RayOrigin; float tCA = dot(L, RayDirection); if (tCA < 0) return -1; float lenL = length(L); float D2 = (lenL*lenL) - (tCA*tCA); float Radius2 = (Radius*Radius); if (D2<=Radius2) { float tHC = sqrt(Radius2 - D2); t0 = tCA-tHC; t1 = tCA+tHC; } else return -1; return t1; } float RayleighPhaseFunction(float cosTheta) { return ((3/(16*PI))*(1+cosTheta*cosTheta)); } float OpticalDepth(float3 StartPosition, float3 EndPosition) { float3 Direction = normalize(EndPosition - StartPosition); float RayLength = RaySphereIntersection(StartPosition, Direction, float3(0, 0, 0), OutterRadius); float SampleLength = RayLength / Isteps; float3 tmpPos = StartPosition + 0.5 * SampleLength * Direction; float tmp; for (int i=0; i<Isteps; i++) { tmp += Density(length(tmpPos)-InnerRadius); tmpPos += SampleLength * Direction; } return tmp*SampleLength; } static float fExposure = -2; float3 HDR( float3 LDR) { return 1.0f - exp( fExposure * LDR ); } [numthreads(32, 32, 1)] //disptach 8, 8, 1 it's 256 by 256 image void ComputeSky(uint3 DTID : SV_DispatchThreadID) { float X = ((2 * DTID.x) / 255) - 1; float Y = 1 - ((2 * DTID.y) / 255); float r = sqrt(((X*X)+(Y*Y))); float Theta = r * (PI); float Phi = atan2(Y, X); static float3 Eye = float3(0, 10, 0); float ViewOD = 0, SunOD = 0, tmpDensity = 0; float3 Attenuation = 0, tmp = 0, Irgb = 0; //if (r<=1) { float3 ViewDir = normalize(float3(sin(Theta)*cos(Phi), cos(Theta),sin(Theta)*sin(Phi) )); float ViewRayLength = RaySphereIntersection(Eye, ViewDir, float3(0, 0, 0), OutterRadius); float SampleLength = ViewRayLength / Ksteps; //vSunDir = normalize(vSunDir); float cosTheta = dot(normalize(vSunDir), ViewDir); float3 tmpPos = Eye + 0.5 * SampleLength * ViewDir; for(int k=0; k<Ksteps; k++) { float SunRayLength = RaySphereIntersection(tmpPos, vSunDir, float3(0, 0, 0), OutterRadius); float3 TopAtmosphere = tmpPos + SunRayLength*vSunDir; ViewOD = OpticalDepth(Eye, tmpPos); SunOD = OpticalDepth(tmpPos, TopAtmosphere); tmpDensity = Density(length(tmpPos)-InnerRadius); Attenuation = exp(-RayleighCoeffs*(ViewOD+SunOD)); tmp += tmpDensity*Attenuation; tmpPos += SampleLength * ViewDir; } Irgb = RayleighCoeffs*RayleighPhaseFunction(cosTheta)*tmp*SampleLength; SkyColors[DTID.xy] = float4(Irgb, 1); } }  
    • By amadeus12
      I made my obj parser
      and It also calculate tagent space for normalmap.
      it seems calculation is wrong..
      any good suggestion for this?
      I can't upload my pics so I link my question.
      https://gamedev.stackexchange.com/questions/147199/how-to-debug-calculating-tangent-space
      and I uploaded my code here


      ObjLoader.cpp
      ObjLoader.h
    • By Alessandro Pozzer
      Hi guys, 

      I dont know if this is the right section, but I did not know where to post this. 
      I am implementing a day night cycle on my game engine and I was wondering if there was a nice way to interpolate properly between warm colors, such as orange (sunset) and dark blue (night) color. I am using HSL format.
      Thank  you.
    • By thefoxbard
      I am aiming to learn Windows Forms with the purpose of creating some game-related tools, but since I know absolutely nothing about Windows Forms yet, I wonder:
      Is it possible to render a Direct3D 11 viewport inside a Windows Form Application? I see a lot of game editors that have a region of the window reserved for displaying and manipulating a 3D or 2D scene. That's what I am aiming for.
      Otherwise, would you suggest another library to create a GUI for game-related tools?
       
      EDIT:
      I've found a tutorial here in gamedev that shows a solution:
      Though it's for D3D9, I'm not sure if it would work for D3D11?
       
    • By Cyndanera
      in directx I need to know how would I play the animation in directx rendering frames for each part of the model moving parts - like the bones, how would would that work?
      I'm new to writing a animation player, for a model parser.
      I'm asking so I understand how to do this, I'm new to loading a model and playing\moving the bones to effect the mesh.
  • Popular Now