Sign in to follow this  

DX11 [SlimDX / D3D11] - Loading effects

This topic is 2793 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

Today has been a painful introduction to Direct3D 11 for me. I have successfully got a device initiated and displaying a blank screen (no geometry). I'm now trying to load and apply an effect to get some geometry showing. Unfortunately, the loading and usage of an effect is tripping me up. I think the problem is down to the fact that I'm targetting 'FeatureLevel.Level_9_1' but I'm not sure. Here is my fx file, as simple as can be:
struct VS_IN
{
	float4 pos : POSITION;
};

struct PS_IN
{
	float4 pos : SV_POSITION;
};

PS_IN vs_main(VS_IN input)
{
	PS_IN output = (PS_IN)0;
	output.pos = input.pos;
	return output;
}

float4 ps_main(PS_IN input) : SV_Target
{
	return float4(1, 0, 0, 1);
}

technique Render
{
	pass P0
	{
		SetVertexShader(CompileShader(vs_2_0, vs_main()));
		SetPixelShader (CompileShader(ps_2_0, ps_main()));
	}
}


Note that it's simple vertex / pixel shader. And this is me trying to load the effect:
ShaderBytecode effectByteCode = ShaderBytecode.CompileFromFile("Default.fx", "Render", "fx_5_0", /*"vs_4_0_level_9_1", */ShaderFlags.EnableStrictness, EffectFlags.None);
Effect effect = new Effect(this.device, this.effectByteCode, EffectFlags.None);


The loads succeeds (although I'm unsure if it's 'safe' to use the "fx_5_0" profile when targetting Direct3D 9, and vertex / pixel shaders 2.0)? The 'vs_4_0_level_9_1' comment was an alternative profile that I tried, with no success. The problem occurs when I try to use the effect:
EffectTechnique tech = effect.GetTechniqueByIndex(0);
                    EffectPass pass = tech.GetPassByIndex(0);

                    InputLayout input = new InputLayout(this.device, pass.Description.Signature, new InputElement[]
                    {
                        new InputElement("POSITION0", 0, Format.R32G32B32_Float, 0, 0)
                    });


GetTechniqueByIndex fails with 'ID3DX11Effect::GetTechniqueByIndex: Invalid technique index (0)', which doesn't cause SlimDX to except until the InputLayout instance is created. I've tried the same with the following:
EffectTechnique tech = effect.GetTechniqueByName("Render");
                    EffectPass pass = tech.GetPassByIndex(0);

                    InputLayout input = new InputLayout(this.device, pass.Description.Signature, new InputElement[]
                    {
                        new InputElement("POSITION0", 0, Format.R32G32B32_Float, 0, 0)
                    });


But then the GetTechniqueByName method excepts with 'Attempted to read or write protected memory. This is often an indication that other memory is corrupt.' I'm not sure where I'm going wrong - if my shader code is wrong, if it's compiled incorrectly for Direct3D 9, etc. Hopefully someone can help me? Thanks.

Share this post


Link to post
Share on other sites
I tried 'fx_2_0', and got the exception '[7860] Effects11: Effect version is unrecognized. This runtime supports fx_5_0 to fx_5_0.'. It may just be a weird error message, but that suggests to me that ONLY the fx_5_0 is supported.

I also tried 'vs_4_0_level_9_1', but I get the exception 'error X3501: 'Render': entrypoint not found'. I'm not sure what an entry point in terms of an effect file, but I assumed 'Render' would be it..!

Share this post


Link to post
Share on other sites
As far as I can tell, neither is valid - if it's null I get the exception:

"String reference not set to an instance of a String.
Parameter name: s"

If set it to be empty string, I get another exception

"Index was outside the bounds of the array."

I thought I couldn't use 'technique10' when using the 'FeatureLevel.Level_9_1' feature level?

Thanks for your help so far.

Share this post


Link to post
Share on other sites
Dunno. I'm just guessing. I hadn't ever been able to get effects in D3D11 working properly, although I didn't try very hard. It's the main reason we don't have D3D11 samples in SlimDX yet.

Share this post


Link to post
Share on other sites
I did wonder why there weren't any. I also wondered why Effect.FromFile was missing - is the effects framework unfinished in SlimDX perhaps?

In fact, should I even be loading effect files with ShaderBytecode.CompileFromFile I wonder? It looks to me like a shader compilation function, and not an effects one...

Share this post


Link to post
Share on other sites
Effects11 (the underlying native library) is rather different than the previous versions of the effect framework. You're supposed to compile the effect to bytecode and load that, there isn't a 'from file' method any longer.

Share this post


Link to post
Share on other sites
I got a bit further! Not necessarily in the right direction. I made file a plain vertex shader (no techniques, passes, etc).
struct VS_IN
{
float4 pos : POSITION;
};

struct PS_IN
{
float4 pos : SV_POSITION;
};

PS_IN vs_main(VS_IN input)
{
PS_IN output = (PS_IN)0;
output.pos = input.pos;
return output;
}


And tried to load and it as follows:

effectByteCode = ShaderBytecode.CompileFromFile("Default2.fx", "vs_main", "vs_4_0_level_9_1", ShaderFlags.None, EffectFlags.None);
vertexShader = new VertexShader(this.device, effectByteCode);

[...]

InputLayout input = new InputLayout(this.device, ShaderSignature.GetInputSignature(this.effectByteCode), new InputElement[]
{
new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0)
});

context.VertexShader.Set(this.vertexShader);


The shader appears to be loaded, but falls on creating the InputLayout with this error:

'[7560] D3D11: ERROR: ID3D11Device::CreateInputLayout: Input Signature in bytecode could not be parsed. Data may be corrupt or in an unrecognizable format. [ STATE_CREATION ERROR #161: CREATEINPUTLAYOUT_UNPARSEABLEINPUTSIGNATURE ]'

Share this post


Link to post
Share on other sites
You have to use technique11, the others will not work when using Effects11 API.

You have to compile with "fx_5_0", nothing else will work when using Effects11 API.

In your effect file, you have to compile for your target: which is 9_1, not 2_0 when using feature levels.



SetVertexShader(CompileShader(vs_4_0_level_9_1, vs_main()));


Share this post


Link to post
Share on other sites
A-ha! That seems to have done the trick.

I'm not getting any output but the effect is loaded. I'm getting another message in DebugView:

[7808] D3D11: WARNING: ID3D11DeviceContext::Draw: Vertex Buffer at the input vertex slot 0 is not big enough for what the Draw*() call expects to traverse. This is OK, as reading off the end of the Buffer is defined to return 0. However the developer probably did not intend to make use of this behavior. [ EXECUTION WARNING #356: DEVICE_DRAW_VERTEX_BUFFER_TOO_SMALL ]

But I think I might have an idea what the problem is.


Thank you both.

@ DieterVW - So this effect, despite having a 'technique11' will work on the Level_9_1 feature level? And will render correctly to Direct3D9 hardware? The 'vs_4_0_level_9_1' string suggests to me that it'll only work on Direct3D9 hardware that supports Vertex Shaders 4.0. Is that right?

Thanks again. :D

Share this post


Link to post
Share on other sites
There's a problem with the Get*Signature methods of the ShaderSignature class. The source in the SVN repository has an additional constructor for InputLayout that takes a full shader bytecode, but we're still working on fixing the shader signature methods.

Share this post


Link to post
Share on other sites
Quote:
Original post by Mike.Popoloski
There's a problem with the Get*Signature methods of the ShaderSignature class. The source in the SVN repository has an additional constructor for InputLayout that takes a full shader bytecode, but we're still working on fixing the shader signature methods.


The InputLayout methods work when using effect.GetTechniqueByIndex(...).GetPassByIndex(...).Description.Signature, but not when using a ShaderSignature obtained using the ShaderSignature.Get*Signature() methods currently, although the fix in the SVN solves that.

As for feature levels, I've never managed to get the effects system to work properly with anything under Level_9_3. Is there any reason you can't target this instead of 9_1? I could give you some pointers then.

Quote:
Original post by jpetrie
Dunno. I'm just guessing. I hadn't ever been able to get effects in D3D11 working properly, although I didn't try very hard. It's the main reason we don't have D3D11 samples in SlimDX yet.


It's not as easy as it could be, but it does work with the Feb release. If you want a hand with producing samples I can provide code.

Share this post


Link to post
Share on other sites
The feature level targets are a bit confusing, but here is what happens. When running a feature 10Level9, the entire runtime will start making only DX9 DDI driver calls. So you are constrained to using features that exist only in DX9 and having to use shaders that are compiled to be used with the DX10 runtime, but target the DX9 driver.

These 10Level9 shaders contain 2 shader blobs, one is 9_x and one is 4_0, depending on the device, the runtime will make use of the correct shader blob for you.

Share this post


Link to post
Share on other sites
Quote:
Original post by adt7
It's not as easy as it could be, but it does work with the Feb release. If you want a hand with producing samples I can provide code.


I'd find that very helpful.

This my entire test project (which still isn't work properly - it should render a triangle using WARP... but doesn't). I at least got around the effect loading problems though..!

If anyone can spot the problem, please let me know. I'll persevere and update if I solve it.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SlimDX.Direct3D11;
using SlimDX.DXGI;
using SlimDX;

using Device = SlimDX.Direct3D11.Device;
using Buffer = SlimDX.Direct3D11.Buffer;
using System.Runtime.InteropServices;

namespace TestDirect3D11
{
public partial class Form1 : Form
{
private Device device;
private SwapChain swapChain;
private RenderTargetView renderTargetView;
private Texture2D texture;
private Buffer vertexBuffer;

private ShaderBytecode effectByteCode;
private Effect defaultEffect;

public Form1()
{
InitializeComponent();

// Create the swap chain description
SwapChainDescription swapChainDescription = new SwapChainDescription()
{
BufferCount = 2,
IsWindowed = true,
Flags = SwapChainFlags.None,
ModeDescription = new ModeDescription(this.Width, this.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm),
OutputHandle = this.Handle,
SampleDescription = new SampleDescription(1, 0),
SwapEffect = SwapEffect.Discard,
Usage = Usage.RenderTargetOutput
};

// Create the Direct3D11 device, using the WARP driver, and targetting Direct3D 9
Device.CreateWithSwapChain(null, DriverType.Warp, DeviceCreationFlags.None, new FeatureLevel[] { FeatureLevel.Level_9_1 }, swapChainDescription, out this.device, out this.swapChain);
this.ResizeBackBuffer();

// Load the vertex buffer
Vector4[] vertices =
{
new Vector4(50F, 0F, 1F, 1F),
new Vector4(100F, 100F, 1F, 1F),
new Vector4(0F, 100F, 1F, 1F)
};

int stride = Marshal.SizeOf(typeof(Vector4));
int length = stride * vertices.Length;

using (DataStream vertexDataStream = new DataStream(vertices, true, true))
{
this.vertexBuffer = new Buffer(this.device, vertexDataStream,
new BufferDescription(length, ResourceUsage.Default, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, stride));
}

string errors;
this.effectByteCode = ShaderBytecode.CompileFromFile("Default.fx", "vs_main", "fx_5_0", ShaderFlags.None, EffectFlags.None, null, null, out errors);
this.defaultEffect = new Effect(this.device, this.effectByteCode, EffectFlags.None);
}

private void ResizeBackBuffer()
{
// Dispose of the previous render target view
if (this.renderTargetView != null)
this.renderTargetView.Dispose();

// Resize the swap chain buffers
this.swapChain.ResizeBuffers(2, this.Width, this.Height, Format.R8G8B8A8_UNorm, SwapChainFlags.None);

// Create the new render target view
using (Texture2D backBuffer = Texture2D.FromSwapChain<Texture2D>(this.swapChain, 0))
{
this.renderTargetView = new RenderTargetView(this.device, backBuffer);
}
}

protected override void OnPaint(PaintEventArgs e)
{
if (swapChain != null)
{
try
{
DeviceContext context = this.device.ImmediateContext;

context.ClearRenderTargetView(this.renderTargetView, new Color4(0F, 0F, 0F));

EffectTechnique tech = this.defaultEffect.GetTechniqueByIndex(0);
EffectPass pass = tech.GetPassByIndex(0);

ShaderSignature shaderSignature = pass.Description.Signature;
InputLayout input = new InputLayout(this.device, shaderSignature, new InputElement[]
{
new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0)
});

this.defaultEffect.GetVariableByName("worldViewProjection").AsMatrix().SetMatrix(Matrix.OrthoOffCenterLH(0F, this.Width, this.Height, 0F, 0F, 100F));

context.InputAssembler.InputLayout = input;
context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(this.vertexBuffer, Marshal.SizeOf(typeof(Vector4)), 0));
for (int i = 0; i < tech.Description.PassCount; ++i)
{
tech.GetPassByIndex(i).Apply(context);
context.Draw(3, 0);
}

this.swapChain.Present(0, PresentFlags.None);
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.ToString());
}
}

base.OnPaint(e);
}

protected override void OnResize(EventArgs e)
{
this.ResizeBackBuffer();
base.OnResize(e);
}

protected override void OnPaintBackground(PaintEventArgs e)
{
//base.OnPaintBackground(e);
}

protected override void OnFormClosed(FormClosedEventArgs e)
{
// Dispose of the Direct3D resources
this.effectByteCode.Dispose();
this.defaultEffect.Dispose();
this.vertexBuffer.Dispose();
this.renderTargetView.Dispose();
this.swapChain.Dispose();
this.device.Dispose();

base.OnFormClosed(e);
}
}
}






Default.fx

float4x4 worldViewProjection;

struct VS_IN
{
float4 Position : POSITION0;
};

struct PS_IN
{
float4 Position : SV_POSITION;
};


// -------------
// Vertex Shader
// -------------
PS_IN vs_main(VS_IN input) : SV_POSITION
{
PS_IN output;
output.Position = mul(input.Position, worldViewProjection);
return output;
}

// ------------
// Pixel Shader
// ------------
float4 ps_main(PS_IN input) : SV_TARGET
{
return float4(1, 1, 1, 1);
}


// ----------
// Techniques
// ----------
technique11 Render
{
pass Pass_0
{
SetVertexShader(CompileShader(vs_4_0_level_9_1, vs_main()));
SetPixelShader(CompileShader(ps_4_0_level_9_1, ps_main()));
}
}


I know it doesn't clean things up and is generally horribly written. I'll tidy it up once it works! :p

Share this post


Link to post
Share on other sites
First of all, don't use OnPaint as a real-time rendering mechanism. It's not designed for that. Reasoning.

As for your problem, you're missing two crucial steps:
1. You need to actual set your render target to the output merger.
2. You need to set a viewport.

For example:

device.ImmediateContext.OutputMerger.SetTargets(renderTargetView);
device.ImmediateContext.Rasterizer.SetViewports(new Viewport(0, 0, ClientSize.Width, ClientSize.Height));

Share this post


Link to post
Share on other sites
Hurray! It works! Thanks for the tip about using OnPaint, this was only a test app, but it's good information to know as it probably would've crept into an actual project.

EDIT: How do I stop the MessagePump? My application excepts when the form is closed when I use it. Specifically:

ObjectDisposedException at Application.Run(new Form1());

Cannot access a disposed object.
Object name: 'Form1'.

Share this post


Link to post
Share on other sites

This topic is 2793 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.

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  

  • Forum Statistics

    • Total Topics
      628722
    • Total Posts
      2984396
  • Similar Content

    • By GreenGodDiary
      Having some issues with a geometry shader in a very basic DX app.
      We have an assignment where we are supposed to render a rotating textured quad, and in the geometry shader duplicate this quad and offset it by its normal. Very basic stuff essentially.
      My issue is that the duplicated quad, when rendered in front of the original quad, seems to fail the Z test and thus the original quad is rendered on top of it.
      Whats even weirder is that this only happens for one of the triangles in the duplicated quad, against one of the original quads triangles.

      Here's a video to show you what happens: Video (ignore the stretched textures)

      Here's my GS: (VS is simple passthrough shader and PS is just as basic)
      struct VS_OUT { float4 Pos : SV_POSITION; float2 UV : TEXCOORD; }; struct VS_IN { float4 Pos : POSITION; float2 UV : TEXCOORD; }; cbuffer cbPerObject : register(b0) { float4x4 WVP; }; [maxvertexcount(6)] void main( triangle VS_IN input[3], inout TriangleStream< VS_OUT > output ) { //Calculate normal float4 faceEdgeA = input[1].Pos - input[0].Pos; float4 faceEdgeB = input[2].Pos - input[0].Pos; float3 faceNormal = normalize(cross(faceEdgeA.xyz, faceEdgeB.xyz)); //Input triangle, transformed for (uint i = 0; i < 3; i++) { VS_OUT element; VS_IN vert = input[i]; element.Pos = mul(vert.Pos, WVP); element.UV = vert.UV; output.Append(element); } output.RestartStrip(); for (uint j = 0; j < 3; j++) { VS_OUT element; VS_IN vert = input[j]; element.Pos = mul(vert.Pos + float4(faceNormal, 0.0f), WVP); element.Pos.xyz; element.UV = vert.UV; output.Append(element); } }  
      I havent used geometry shaders much so im not 100% on what happens behind the scenes.
      Any tips appreciated! 
    • By mister345
      Hi, I'm building a game engine using DirectX11 in c++.
      I need a basic physics engine to handle collisions and motion, and no time to write my own.
      What is the easiest solution for this? Bullet and PhysX both seem too complicated and would still require writing my own wrapper classes, it seems. 
      I found this thing called PAL - physics abstraction layer that can support bullet, physx, etc, but it's so old and no info on how to download or install it.
      The simpler the better. Please let me know, thanks!
    • By Hexaa
      I try to draw lines with different thicknesses using the geometry shader approach from here:
      https://forum.libcinder.org/topic/smooth-thick-lines-using-geometry-shader
      It seems to work great on my development machine (some Intel HD). However, if I try it on my target (Nvidia NVS 300, yes it's old) I get different results. See the attached images. There
      seem to be gaps in my sine signal that the NVS 300 device creates, the intel does what I want and expect in the other picture.
      It's a shame, because I just can't figure out why. I expect it to be the same. I get no Error in the debug output, with enabled native debugging. I disabled culling with CullMode.None. Could it be some z-fighting? I have little clue about it but I tested to play around with the RasterizerStateDescription and DepthBias properties with no success, no change at all. Maybe I miss something there?
      I develop the application with SharpDX btw.
      Any clues or help is very welcome
       


    • By Beny Benz
      Hi,
      I'm currently trying to write a shader which shoud compute a fast fourier transform of some data, manipulating the transformed data, do an inverse FFT an then displaying the result as vertex offset and color. I use Unity3d and HLSL as shader language. One of the main problems is that the data should not be passed from CPU to GPU for every frame if possible. My original plan was to use a vertex shader and do the fft there, but I fail to find out how to store changing data betwen shader calls/passes. I found a technique called ping-ponging which seems to be based on writing and exchangeing render targets, but I couldn't find an example for HLSL as a vertex shader yet.
      I found https://social.msdn.microsoft.com/Forums/en-US/c79a3701-d028-41d9-ad74-a2b3b3958383/how-to-render-to-multiple-render-targets-in-hlsl?forum=xnaframework
      which seem to use COLOR0 and COLOR1 as such render targets.
      Is it even possible to do such calculations on the gpu only? (/in this shader stage?, because I need the result of the calculation to modify the vertex offsets there)
      I also saw the use of compute shaders in simmilar projects (ocean wave simulation), do they realy copy data between CPU / GPU for every frame?
      How does this ping-ponging / rendertarget switching technique work in HLSL?
      Have you seen an example of usage?
      Any answer would be helpfull.
      Thank you
      appswert
    • By ADDMX
      Hi
      Just a simple question about compute shaders (CS5, DX11).
      Do the atomic operations (InterlockedAdd in my case) should work without any issues on RWByteAddressBuffer and be globaly coherent ?
      I'v come back from CUDA world and commited fairly simple kernel that does some job, the pseudo-code is as follows:
      (both kernels use that same RWByteAddressBuffer)
      first kernel does some job and sets Result[0] = 0;
      (using Result.Store(0, 0))
      I'v checked with debugger, and indeed the value stored at dword 0 is 0
      now my second kernel
      RWByteAddressBuffer Result;  [numthreads(8, 8, 8)] void main() {     for (int i = 0; i < 5; i++)     {         uint4 v0 = DoSomeCalculations1();         uint4 v1 = DoSomeCalculations2();         uint4 v2 = DoSomeCalculations3();                  if (v0.w == 0 && v1.w == 0 && v2.w)             continue;         //    increment counter by 3, and get it previous value         // this should basically allocate space for 3 uint4 values in buffer         uint prev;         Result.InterlockedAdd(0, 3, prev);                  // this fills the buffer with 3 uint4 values (+1 is here as the first 16 bytes is occupied by DrawInstancedIndirect data)         Result.Store4((prev+0+1)*16, v0);         Result.Store4((prev+1+1)*16, v1);         Result.Store4((prev+2+1)*16, v2);     } } Now I invoke it with Dispatch(4,4,4)
      Now I use DrawInstancedIndirect to draw the buffer, but ocassionaly there is missed triangle here and there for a frame, as if the atomic counter does not work as expected
      do I need any additional synchronization there ?
      I'v tried 'AllMemoryBarrierWithGroupSync' at the end of kernel, but without effect.
      If I do not use atomic counter, and istead just output empty vertices (that will transform into degenerated triangles) the all is OK - as if I'm missing some form of synchronization, but I do not see such a thing in DX11.
      I'v tested on both old and new nvidia hardware (680M and 1080, the behaviour is that same).
       
  • Popular Now